Laravel删除多对多关系中的Pivot数据

Rob*_*Rob 0 php tags pivot-table laravel

不确定我是否正确设置了它.在Laravel中,我创建了两个具有多对多关系的模型

模型是ItemTags.每个包含一个belongsTo到另一个.

当我运行这样的查询时:

Item::with('tags')->get();
Run Code Online (Sandbox Code Playgroud)

它返回包含集合的items每个项目的tags集合.但是,集合中的每个标记还包含pivot我不需要的数据.这是json格式:

[{
    "id":"49",
    "slug":"test",
    "order":"0","tags":[
        {"id":"3","name":"Blah","pivot":{"item_id":"49","tag_id":"3"}},
        {"id":"13","name":"Moo","pivot":{"item_id":"49","tag_id":"13"}}
    ]
}]
Run Code Online (Sandbox Code Playgroud)

无论如何都要阻止这些数据进入

luk*_*ter 8

你问过,你会得到你的答案.但首先要总结一下评论部分.我个人不知道为什么你会想要/需要这样做.我理解你是否想要从输出中隐藏它但不从数据库中选择它确实没有真正的好处.当然,传输的数据越少,数据库服务器的工作量就会越来越少,但您不会以任何方式注意到这一点.

但是有可能.它不是很漂亮,因为你必须覆盖这个belongsToMany类.

首先,新的关系类:

class BelongsToManyPivotless extends BelongsToMany {
    /**
     * Hydrate the pivot table relationship on the models.
     *
     * @param  array  $models
     * @return void
     */
    protected function hydratePivotRelation(array $models)
    {
        // do nothing
    }

    /**
     * Get the pivot columns for the relation.
     *
     * @return array
     */
    protected function getAliasedPivotColumns()
    {
        return array();
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,这个类重写了两个方法.hydratePivotRelation通常会创建枢轴模型并用数据填充它.getAliasedPivotColumns将返回所有列的数组以从数据透视表中进行选择.

现在我们需要将它集成到我们的模型中.我建议你使用一个BaseModel类,但它也可以在模型中直接使用.

class BaseModel extends Eloquent {

    public function belongsToManyPivotless($related, $table = null, $foreignKey = null, $otherKey = null, $relation = null){
        if (is_null($relation))
        {
            $relation = $this->getBelongsToManyCaller();
        }

        $foreignKey = $foreignKey ?: $this->getForeignKey();

        $instance = new $related;

        $otherKey = $otherKey ?: $instance->getForeignKey();

        if (is_null($table))
        {
            $table = $this->joiningTable($related);
        }

        $query = $instance->newQuery();

        return new BelongsToManyPivotless($query, $this, $table, $foreignKey, $otherKey, $relation);
    }
}
Run Code Online (Sandbox Code Playgroud)

为了简洁起见,我编辑了评论,但其他方法就像belongsToMany来自Illuminate\Database\Eloquent\Model.当然除了创建的关系类.在这里我们使用自己的BelongsToManyPivotless.

最后,这就是你如何使用它:

class Item extends BaseModel {
    public function tags(){
        return $this->belongsToManyPivotless('Tag');
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 但是为什么所有这些呢?您只需要在模型中这样做:protected $ hidden = ['pivot']; (2认同)
  • 另一个用例是“unions”,您可以在其中获取“SQLSTATE[21000]:基数违规:1222 使用的 SELECT 语句具有不同数量的列” (2认同)

Ami*_*Dev 5

您可以像这样在模型的隐藏部分中添加字段名称:

protected $ hidden = ['pivot'];

就是这样,它对我来说很好用。