簡體   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