在模型中使用两个用户关系

在模型中使用两个用户关系

本文介绍了Laravel,在模型中使用两个用户关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

连接模型:

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');
}

控制器:

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]);
}

刀片:

@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

我在我的模型Connection.php中与用户建立了两个关系。我得到错误:尝试获取非对象的属性在刀片中的第2和第5行。

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.

推荐答案

第一个变化:

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

而不是这样:

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]);
}

你可以做:

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' }}

但说实话很难得到你真正想要实现的东西 - 你正在使用奇怪的功能 whereUser_id_1AndConnection_status 你应该不这样做可能你应该仔细阅读为Laravel。

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.

这篇关于Laravel,在模型中使用两个用户关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:37