Laravel:如何创建自定义枢轴模型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21203542/
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: How do I create a custom pivot model?
提问by Robin
I'm working on a project that has a many to many relationship between User
and Club
. This relationship works and I can get the respective objects with: $user->clubs
. The pivot table I've named memberships
. I can get the pivot data with $club->pivot
. Foreign keys are defined for the memberships
table in migrations.
我正在从事一个在User
和之间具有多对多关系的项目Club
。这种关系的工作,我可以得到相应的对象:$user->clubs
。我命名的数据透视表memberships
。我可以使用$club->pivot
. 为memberships
迁移中的表定义了外键。
However, I'd like the pivot table to be represented by a model so that I can easily update attributes of Membership
such as role (Or even add a Role
model to Membership
!) or status
.
但是,我希望数据透视表由模型表示,以便我可以轻松更新Membership
角色(甚至将Role
模型添加到Membership
!)或status
.
I've looked at "Defining A Custom Pivot Model" in the docs, but what it says doesn't work for me, I get:
我在文档中查看了“定义自定义枢轴模型”,但它所说的对我不起作用,我得到:
ErrorException
Argument 1 passed to Illuminate\Database\Eloquent\Model::__construct() must be of the type array, object given
ErrorException
Argument 1 passed to Illuminate\Database\Eloquent\Model::__construct() must be of the type array, object given
I've also looked at this descriptionof how to do it, but it's more or less the same as above.
Membership
model:
Membership
模型:
class Membership extends Eloquent {
protected $table = 'memberships';
public function user()
{
return $this->belongsTo('User');
}
public function club()
{
return $this->belongsTo('Club');
}
}
Has anyone done this before?
以前有人这样做过吗?
采纳答案by Robin
This has been solved by a suggestion by a reddit userto extend Pivot
in my Membership model. I also had to add ->withPivot('status', 'role')->withTimestamps()
to the relationship declarations in the User and Club models.
这已通过 reddit 用户的建议解决,以扩展Pivot
我的会员模型。我还必须->withPivot('status', 'role')->withTimestamps()
在 User 和 Club 模型中添加关系声明。
回答by Margus Pala
You can do this by adding some manual code.
您可以通过添加一些手动代码来做到这一点。
Your Membership model looks ok. You can get all clubs of a $user easily if you define method $user->clubs() where you get all the clubs manually.
您的 Membership 模型看起来不错。如果您定义方法 $user->clubs() 手动获取所有俱乐部,则可以轻松获取 $user 的所有俱乐部。
clubs() {
$memberships=$this->memberships;
$clubs=new \Illuminate\Database\Eloquent\Collection();
foreach($memberships as $m) {
$clubs=$clubs->merge($m->clubs);
}
return $clubs;
}