laravel LaravelbelongsToMany 排除数据透视表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26474201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel belongsToMany exclude pivot table
提问by Patrick Reck
I have two models, User
and Badge
. A user can have multiple badges, and a badge can belong to multiple users. (using a pivot table)
我有两个模型,User
和Badge
. 一个用户可以有多个徽章,一个徽章可以属于多个用户。(使用数据透视表)
Currently I am getting the data I need, but additionally I am getting the pivot
table along. How do I exclude this?
目前我正在获取我需要的数据,但另外我正在获取pivot
表格。我如何排除这个?
Here's the User
model:
这是User
模型:
class User extends Eloquent {
public function badges() {
return $this->belongsToMany('Badge', 'users_badges');
}
}
And the Badge
model:
和Badge
模型:
class Badge extends Eloquent {
public function users() {
return $this->belongsToMany('User', 'users_badges');
}
}
回答by c-griffin
Add pivot
to your $hidden
property's array in your model(s).
添加pivot
到您$hidden
的模型中的属性数组。
class Badge extends Eloquent {
protected $hidden = ['pivot'];
public function users() {
return $this->belongsToMany('User', 'users_badges');
}
}
And same with your User
model
和你的User
模型一样
class User extends Eloquent {
protected $hidden = ['pivot'];
public function badges() {
return $this->belongsToMany('Badge', 'users_badges');
}
}
回答by bmatovu
Or you can still hide the pivot on demandthis way...
或者您仍然可以通过这种方式按需隐藏枢轴......
$user = User::find(1);
$user->badges->makeHidden('pivot');
$badge = Badge::find(1);
$badge->users->makeHidden('pivot');