不确定我是否正确设置了。在Laravel中,我正在创建两个具有多对可能关系的模型。
模型Item
和Tags
.每个都包含对另一个的belongsTo
。
当我运行这样的查询时:
Item::with('tags')->get();
它返回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"}}
]
}]
无论如何可以防止这些数据进入
模型的隐藏部分中添加字段的名称,如下所示:
protected $hidden = ['pivot'];
就是这样,它对我很好用。
你已经问过了,你会得到你的答案。但首先用几句话来总结评论部分。我个人不知道你为什么想要/需要这样做。我了解您是否想从输出中隐藏它但不从数据库中选择它真的没有真正的好处。当然,传输的数据会更少,数据库服务器要做的工作也少一点点,但你不会以任何方式注意到这一点。
但是这是可能的。不过它不是很漂亮,因为您必须覆盖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();
}
}
如您所见,此类覆盖了两个方法。 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);
}
}
为了简洁起见,我编辑了注释,但除此之外,该方法就像Illuminate'Database'Eloquent'Model
中的belongsToMany
一样。当然,除了创建的关系类。在这里我们使用我们自己的BelongsToManyPivotless
.
最后,这是您使用它的方式:
class Item extends BaseModel {
public function tags(){
return $this->belongsToManyPivotless('Tag');
}
}
如果您想删除透视数据,则可以按照protected $hidden = ['pivot'];
@Amine_Dev建议使用,所以我使用了它,但它对我不起作用,
但问题确实是我在错误的模型中使用它,所以我想在其中提供更多细节,在哪里使用它,所以你们不要为我一直在努力的问题而苦苦挣扎。
因此,如果您以以下方式获取数据:
Item::with('tags')->get();
然后你必须将透视分配给隐藏数组,如下所示
但请记住,您必须Tag
模型中定义它,而不是Item
模型中定义它
class Tag extends Model {
protected $hidden = ['pivot'];
}
两种可能的方法
1. 在生成的模型上使用 makeHidden 方法
$items = Item::with('tags')->get();
return $items->makeHidden(['pivot_col1', 'pivot_col2']...)
2. 使用PHP的array_column函数
$items = Item::with('tags')->get()->toArray();
return array_column($items, 'tags');