Laravel - 三个模型的数据透视表 - 如何插入相关模型? [英] Laravel - Pivot table for three models - how to insert related models?

查看:21
本文介绍了Laravel - 三个模型的数据透视表 - 如何插入相关模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个具有多对多关系的模型:UserActivityProduct.这些表看起来像 idname.并且在每个模型中都有功能,例如在用户模型中:

I have three models with Many to Many relationships: User, Activity, Product. The tables look like id, name. And in the each model there are functions, for example, in User model:

public function activities()
{
    return $this->belongsToMany('Activity');
}
public function products()
{
    return $this->belongsToMany('Product');
}

数据透视表User_activity_product是:

iduser_idactivity_idproduct_id.目标是获取如下数据:User->activity->products.有可能以这种方式组织这种关系吗?以及如何更新这个数据透视表?

id, user_id, activity_id, product_id. The goal is to get data like: User->activity->products. Is it possible to organize such relations in this way? And how to update this pivot table?

推荐答案

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

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).

你需要像这样定义关系:

You need to define the relations like this:

// 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.

这篇关于Laravel - 三个模型的数据透视表 - 如何插入相关模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆