Laravel, Using two user relationships in model

2019-08-29 05:33发布

问题:

Connection Model :

protected $table = 'connections';
protected $fillable = ['user_id_1','user_id_2','connection_status'];
public function user_id_1()
{
    return $this->belongsTo('App\User', 'user_id_1');
}

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

Controller :

public function show($id){
    $user_id_1_connections = Connection::whereUser_id_1AndConnection_status($id, 1)->get();
    $user_id_2_connections = Connection::whereUser_id_2AndConnection_status($id, 1)->get();
    return view('connection.showConnection',['user_id_1_connections' => $user_id_1_connections, 'user_id_2_connections' => $user_id_2_connections]);
}

Blade:

@foreach($user_id_1_connections as $user_id_1_connection)
{{ $user_id_1_connection->user_id_1 ?  $user_id_1_connection->user_id_1->name : 'unknown' }}
@endforeach
@foreach($user_id_2_connections as $user_id_2_connection)
{{ $user_id_2_connection->user_id_2 ?  $user_id_2_connection->user_id_2->name : 'unknown' }}
@endforeach

I am making two relationships to user in my model Connection.php. I'm getting the error: "Trying to get property of non-object " in line 2nd and 5th in blade.

回答1:

First change:

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

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

into:

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

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

to avoid collisions between table columns and relationships

Instead of this:

public function show($id){
    $user_id_1_connections = Connection::whereUser_id_1AndConnection_status($id, 1)->get();
    $user_id_2_connections = Connection::whereUser_id_2AndConnection_status($id, 1)->get();
    return view('connection.showConnection',['user_id_1_connections' => $user_id_1_connections, 'user_id_2_connections' => $user_id_2_connections]);
}

you can do:

public function show($id){
  return view('connection.showConnection', ['connection' => Connection::findOrFail($id)]);
}

And now your template could look like this:

User 1 name: {{ $connection->user1 ? $connection->user1->name : 'unknown' }}
User 2 name: {{ $connection->user2 ? $connection->user2->name : 'unknown' }}

But to be honest it's hard to get what you really want to achieve - you are using strange function whereUser_id_1AndConnection_status what you should rather don't do so probably you should read carefully relationships documentation for Laravel.