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

查看:107
本文介绍了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,这样它符合雄辩的命名约定,这使生活变得更轻松(我的示例将使用该名称)

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.

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

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