Laravel - 三种型号的枢轴表 - 如何插入相关型号?

vol*_*n80 2 pivot many-to-many relationships laravel-4

我有三个型号,多对多的关系:User,Activity,Product.表格看起来像id,name.并且在每个模型中都有功能,例如,在用户模型中:

public function activities()
{
    return $this->belongsToMany('Activity');
}
public function products()
{
    return $this->belongsToMany('Product');
}
Run Code Online (Sandbox Code Playgroud)

数据透视表User_activity_product是:

id,user_id,activity_id,product_id.目标是获得如下数据:User->activity->products.是否有可能以这种方式组织这种关系?以及如何更新此数据透视表?

Jar*_*zyk 11

首先,我建议您重命名数据透视表,activity_product_user以使其符合Eloquent命名约定,这使得生活更轻松(我的示例将使用该名称).

你需要定义这样的关系:

// User model
public function activities()
{
    return $this->belongsToMany('Activity', 'activity_product_user');
}
public function products()
{
    return $this->belongsToMany('Product', 'activity_product_user');
}
Run Code Online (Sandbox Code Playgroud)

然后你可以获取相关的模型:

$user->activities; // collection of Activity models
$user->activities->find($id); // Activity model fetched from the collection
$user->activities()->find($id); // Activity model fetched from the db

$user->activities->find($id)->products; // collection of Product models related to given Activity
// but not necessarily related in any way to the User

$user->activities->find($id)->products()->wherePivot('user_id', $user->id)->get();
// collection of Product models related to both Activity and User
Run Code Online (Sandbox Code Playgroud)

您可以通过设置自定义Pivot模型,最后一行的帮助关系等来简化这种关系的使用.

对于附加最简单的方法应该将第3个键作为参数传递,如下所示:

$user->activities()->attach($activityIdOrModel, ['product_id' => $productId]);
Run Code Online (Sandbox Code Playgroud)

所以它需要一些额外的代码来使它完美,但它是可行的.