laravel - 访问关注者数据 Laravel 5.8 和 Eloquent
问题描述
我有一个为追随者设置的基表,并且追随者模型与用户模型具有关系 belongsTo 。用户模型与追随者模型有关系belongsToMany。追随者表有“id,follower_id,leader_id”
我正在尝试通过 User 模型访问关注者表,但它不允许我这样做。我一定是做错了什么,但我以前曾与 Eloquent 关系合作过,而且我一直都在工作。有人可以看看下面的代码片段并指出问题所在吗?
用户模型
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');
}
跟随控制器
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>
这会引发“在此实例上找不到属性”的错误。所有的命名空间都是有序的,所以这也不是问题。这里有什么问题?
解决方案
如果您在用户和关注者之间存在一对多关系,则您的关系定义错误,如果关注者属于用户,则用户有许多关注者:
public function followers(){
return $this->hasMany('App\Follower','user_id');
}
看看文档
你的控制器:
public function index($id){
$user = User::find($id);
return view('welcome')->with('user', $user);
}
您可以使用 foreach 循环从用户访问每个关注者:
@foreach($user->followers as $follower)
{{$follower->anyAttributeFromTheFollower}}
@endforeach
推荐阅读
- angular - 为使用 jasmine karma 以数组形式返回 promise 的方法编写单元测试用例
- java - 为什么约束集不起作用我也链接了它们?
- deployment - gcloud 使用任意名称在 cloudbuild 中部署应用程序
- python - 如何在 Heroku 上创建 Flow 对象-凭据
- mysql - 在 MySQL 中添加行值并创建新列
- algorithm - 间隔调度
- java - 完整性检查:为什么在 x 和 x+1 处使用 Graphics.drawLine 绘制的垂直线之间存在间隙?
- amazon-web-services - 白名单 gitlab webhook
- php - AWS ec2 中的 Cron 作业,但无法正常工作
- create-react-app - 如何从 Firebase 托管中取消部署 React Web 应用程序