简体   繁体   中英

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

Relations in project_survey model:

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? 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

So I changed the relation surveys() to get all the survey of the project with the required data:

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:

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

You should access the relationship to load that particular scheduledUser

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


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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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