且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel-三种模型的数据透视表-如何插入相关模型?

更新时间:2023-12-01 13:02:52

首先,我建议您将数据透视表重命名为activity_product_user,这样它符合雄辩的命名约定,这使生活变得更轻松(我的示例将使用该名称)

First I suggest you rename the pivot table to activity_product_user so it complies with Eloquent naming convention what makes the life easier (and my example will use that name).

您需要定义如下关系:

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

然后您可以获取相关模型:

Then you can fetch related models:

$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

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

You can simplify working with such relation by setting up custom Pivot model, helper relation for the last line etc.

要附加最简单的方法,应将第三个密钥作为这样的参数传递:

For attaching the easiest way should be passing the 3rd key as a parameter like this:

$user->activities()->attach($activityIdOrModel, ['product_id' => $productId]);

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

So it requires some additional code to make it perfect, but it's feasible.