Laravel 枢轴:从 withPivot() 获取模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25362859/
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 09:57:42  来源:igfitidea点击:

Laravel pivot: Get model from withPivot()

laravelpivoteloquent

提问by xonorageous

I'm building an application using Laravel 4 but have stumbled across a problem with the pivot tables.

我正在使用 Laravel 4 构建应用程序,但偶然发现了数据透视表的问题。

I've got a user model, an establishment model, & a studyLevel model.

我有一个用户模型、一个建立模型和一个 studyLevel 模型。

For the moment to find the establishment a user has been at I use the following code in my User model:

为了找到用户所在的位置,我在我的用户模型中使用了以下代码:

public function establishments()
{
    return $this->belongsToMany('Establishment')->withPivot('start', 'stop', 'study_level_id')->withTimestamps();
}

The establishment_user (pivot) table has the following columns:

建立用户(枢轴)表具有以下列:

id | establishment_id | user_id | start | stop | study_level_id

To get the list of establishments for a user I use the following in a controller:

要获取用户的场所列表,我在控制器中使用以下内容:

$establishments = $user_repo->find($user_id)
                ->with(['establishments', 'establishments.userSubjects' => function ($query) use ($user)
                {
                    $query->where('user_id', $user->id);
                }])
                ->get();

My problem is that the response gives me the ID of the studyLevel but I would like to have the information from the studyLevel model. Is it possible to get information from the studyLevel table using withPivot() ?

我的问题是响应为我提供了 studyLevel 的 ID,但我想要来自 studyLevel 模型的信息。是否可以使用 withPivot() 从 studyLevel 表中获取信息?

Thanks in advance, all help is appreciated.

提前致谢,感谢所有帮助。

采纳答案by ollieread

The ideal way to do this is to have a Model specifically for your pivot table. There are alternatives whereby you can have relationships defined in models, using the field pivot_study_level_id, but that wouldn't work in every situation and would likely be more trouble than it's worth.

实现此目的的理想方法是为您的数据透视表专门创建一个模型。有一些替代方法,您可以使用字段 pivot_study_level_id 在模型中定义关系,但这不会在所有情况下都有效,而且可能会比它的价值更麻烦。

Just setup a model like Establishment\Userand let that handle the relationships.

只需设置一个模型,Establishment\User然后让它处理关系。