首页 > 解决方案 > 访问关注者数据 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>

这会引发“在此实例上找不到属性”的错误。所有的命名空间都是有序的,所以这也不是问题。这里有什么问题?

标签: laraveleloquent

解决方案


如果您在用户和关注者之间存在一对多关系,则您的关系定义错误,如果关注者属于用户,则用户有许多关注者:

 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

推荐阅读