【发布时间】:2019-04-05 21:25:51
【问题描述】:
我有一个为追随者设置的基表,追随者模型与用户模型有关系belongsTo。用户模型与追随者模型有关系belongsToMany。追随者表有“id,follower_id,leader_id”
我正在尝试通过 User 模型访问关注者表,但它不允许我这样做。我一定是做错了什么,但我以前曾与 Eloquent 关系合作过,而且我一直都在工作。有人可以看看下面的代码 sn-ps 并指出问题所在吗?
用户模型
public function followers(){
return $this->belongsToMany(User::class, 'followers', 'leader_id', 'follower_id')->withTimestamps();
}
public function followings(){
return $this->belongsToMany(User::class, 'followers', 'follower_id', 'leader_id')->withTimestamps();
追随者模式
protected $table = 'followers';
public $primaryKey = 'id';
public $timestamps = true;
public function user(){
$this->belongsTo('App\User');
}
FollowerController
Old controller for old relationship
// public function followUser($id){
// $user = User::find($id);
// if(!$user){
// return redirect()->back()->with('error', 'User does not exist.');
// }
// $user->followers()->attach(auth()->user()->id);
// return redirect()->back()->with('success', 'You now follow the user!');
// }
//New controller
public function followUser($id){
$user = User::find($id);
if(!$user){
return redirect()->back()->with('error', 'User does not exist.');
}
$follow = new Follower;
$follow->follower_id = Auth::user()->id;
$follow->leader_id = $user;
$follow->save();
return redirect()->back()->with('success', 'You now follow the user!');
}
用户控制器
// This is a test function
public function index($id){
$userid = Auth::user();
$user = User::find($id)->followers;
$recipe = Recipe::find(5);
$savedRecipes = Save::where('user_id', '=', $userid);
return view('welcome')->with('recipe', $recipe)->with('user', $user)->with('savedRecipes', $savedRecipes);
}
测试视图
<div class="content">
<div class="title m-b-md">
Welcome to the TestLab: {{$user->followers->follower_id}}
<br>
这会引发“在此实例上找不到属性”的错误。 所有的命名空间都是有序的,所以这也不是问题。 这里有什么问题?
【问题讨论】:
-
一个关注者属于一个用户,一个用户有很多关注者,对吧?
-
我不应该在那里使用belongsToMany吗?
-
仅当一个用户有很多关注者并且一个关注者有很多用户时