我的控制器:
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]);
}
我的模特:
protected $table = 'connections';
protected $fillable = ['user_id_1','user_id_2','connection_status'];
public function user()
{
return $this->belongsTo('App\User');
}
我的刀锋:
@foreach($user_id_1_connections as $user_id_1_connection)
{{ $user_id_1_connection->user->name }}
{{ $comment->user->name }}
@endforeach
@foreach($user_id_2_connections as $user_id_2_connection)
{{ $user_id_2_connection->user->name }}
@endforeach
我已将user_id_1和user_id_2的外键设为用户表。
$table->integer('user_id_1')->unsigned();
$table->foreign('user_id_1')->references('id')->on('users')->onDelete('cascade');
$table->integer('user_id_2')->unsigned();
$table->foreign('user_id_2')->references('id')->on('users')->onDelete('cascade');
但是当我运行这段代码时。它显示错误: 试图获得非对象的属性。
答案 0 :(得分:0)
这里的问题可能是您没有为每个连接分配user
,而不是:
{{ $user_id_1_connection->user->name }}
你应该写这样的东西:
{{ $user_id_1_connection->user ? $user_id_1_connection->user->name : 'unknown' }}
当您使用$x->y->z
语法时,在所有其他位置相同。要显示z
,您应该确保$x->y
不为空