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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:53:20  来源:igfitidea点击:

Laravel: How do I create a custom pivot model?

phplaravellaravel-4

提问by Robin

I'm working on a project that has a many to many relationship between Userand 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 membershipstable 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 Membershipsuch as role (Or even add a Rolemodel 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.

我也看过这个关于如何做的描述,但它或多或少与上面相同。

Membershipmodel:

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 Pivotin 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;
}