フォロワー用のベーステーブルを設定していて、フォロワーモデルにはユーザーモデルとの関係があります。ユーザーモデルには、フォロワーモデルとbelongsToManyの関係があります。フォロワーテーブルには「id、follower_id、leader_id」があります
ユーザーモデルを介してフォロワーテーブルにアクセスしようとしていますが、アクセスできません。私は何か間違ったことをしているに違いありませんが、私は以前に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');
}
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!');
}
UserController
// 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>
これにより、「このインスタンスにプロパティが見つかりません」というエラーがスローされます。すべての名前空間はすべて順番に並んでいるので、それも問題ではありません。ここでの問題は何ですか?
あなたが持っている場合は一対多のユーザーとフォロワーとの関係をフォロワーには、ユーザー、ユーザーに属している場合は、あなたの関係の間違った定義のhasManyフォロワー:
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
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加