繁体   English   中英

Laravel 5.8检索关注者信息

[英]Laravel 5.8 Retrieve information on followers

我有一个用Laravel编写的应用程序的关注用户系统,我正在尝试根据某些关注者从数据库中检索数据。 这是一个包含用户,食谱和关注者表的食谱应用程序。 我目前正在通过编写$ user-> followers来检索用户关注者。 但是,我希望以这种方式建立我的关系,以便可以检索属于给定用户关注者的特定食谱。 与$ user-> followers-> recipes类似的东西。 我现在没有正确的逻辑或雄辩的关系来做到这一点。 关于如何完成的任何建议?

用户模型

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();
    }

配方模型

public function user(){
        return $this->belongsTo('App\User');
    }

    public function category(){
        return $this->belongsTo('App\Category');
    }

    public function comments(){
        return $this->hasMany('App\Comment'); 
    }

    public function likes(){
        return $this->hasMany('App\Like');
    }

FollowerController

class FollowerController extends Controller
{
    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!');
    }

    public function unfollowUser($id){
        $user = User::find($id);

        if(!$user){
            return redirect()->back()->with('error', 'User does not exist.');
        }

        $user->followers()->detach(auth()->user()->id);
        return redirect()->back()->with('success', 'You unfollowed the user!');
    }

    public function show($id){
        $user = User::find($id);
        $followers = $user->followers;
        $followings = $user->followings;

        return view('welcome')->with('user', $user);
    }

有什么方法可以设置用户,配方和关注模型之间的关系? 检索与用户的特定关注者有关的任何信息的最佳方法是什么? 让我知道是否需要与大家分享代码! 谢谢您的帮助!

您需要的是HasManyThrough关系。

在您的用户模型中:

public function recipes()
{
    return $this->hasManyThrough(
        'App\Recipe',
        'App\User',
        'leader_id',
        'user_id',
        'id',
        'id'
    );
}

完整的文档(您可能需要更好地设置一些外键)可以在以下网址找到: https : //laravel.com/docs/5.8/eloquent-relationships#has-many-through

编辑:我错了。 您的followers关系是多对多的关系,而不是一对多的关系,因此这种方法行不通。 如果有人在一对多关系方面遇到麻烦,我将在此留下评论。

您可以通过“跳过” users表来定义直接关系:

class User extends Model
{
    public function followerRecipes() {
        return $this->belongsToMany(
            Recipe::class, 'followers', 'leader_id', 'follower_id', null, 'user_id'
        );
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM