简体   繁体   English

与Laravel到同一张桌子的两个关系

[英]Two relations to same table with Laravel

I have the following table: 我有下表:

**Project_Survey**
id
survey_id
<many_other_fields>
scheduled_user
completed_by

A survey can be scheduled and assigned to a user, but completed by someone else. 可以计划调查并将其分配给用户,但可以由其他人完成。 Both fields are a FK to the table User 这两个字段都是表用户的FK

Relations in project_survey model: project_survey模型中的关系:

public function user()
{
    return $this->belongsTo('App\User', 'completed_by');
}

public function scheduledUser()
{
    return $this->belongsTo('App\User', 'scheduled_user');
}

How can I show both users in a table? 如何在表格中显示两个用户? When I do 当我做

{{ $survey->firstname }}

It returns the firstname of the completed_by user, so how do I get the scheduled user? 它返回completed_by用户的名字,那么如何获得预定用户? This does not seem to work: 这似乎不起作用:

{{ $survey->scheduledUser->firstname }}

Update I made a mistake here: 更新我在这里犯了一个错误:

public function surveys()
{
    return $this
        ->belongsToMany('App\Survey', 'project_survey')
        ->withPivot('id')
        ->leftJoin('user', 'project_survey.completed_by', '=', 'user.id')
        ->select('survey.*', 'project_survey.*', 'user.firstname', 'user.lastname');
}

Here I get all the survey that are linked to this project. 在这里,我得到了与此项目相关的所有调查。

Update 2 更新2

So I changed the relation surveys() to get all the survey of the project with the required data: 因此,我更改了关系surveys(),以获取具有所需数据的所有项目调查:

public function surveys()
{
    return $this
        ->hasMany('App\Project_Survey', 'project_id')
        ->with('survey')
        ->with('scheduledUser')
        ->with('user');
}

And if I do a dump of the $survey I get the 3 relations back, so far so good: 如果我放弃了$ survey,我会得到3个关系,到目前为止,效果很好:

Project_survey {#961 ▼

#table: "project_survey"
#fillable: array:10 [▶]
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []

#attributes: array:15 [▶]
#original: array:15 [▶]

#relations: array:3 [▼
"survey" => Survey {#1015 ▶}
"scheduledUser" => null
"user" => User {#1111 ▶}
]

But I still get an error if I tried to display the data from the relations: 但是,如果我尝试显示关系中的数据,仍然会出错:

  {{ $survey->survey()->number }} 

Undefined property: Illuminate\\Database\\Eloquent\\Relations\\BelongsTo::$number 未定义的属性:Illuminate \\ Database \\ Eloquent \\ Relations \\ BelongsTo :: $ number

You should access the relationship to load that particular scheduledUser 您应该访问关系以加载特定的ScheduledUser

{{ $survey->scheduledUser()->firstname }}


@foreach($survey as $sur)
  {{ $sur->scheduledUser()->firstName }}
@endforeach

最终的解决方案是使用->with('<relation>')来获取@kerbholz建议的相关数据,并在刀片模板中显示数据,如下所示:

{{ $survey->survey->number }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM