2017-05-31 65 views
0

我想實現一個跟隨系統,其中User可以遵循Comment,Category,Post和更多。我曾嘗試使用Laravel Polymorphic關係爲此,但不能包裹我的頭。如果有人能指導我,那將會很棒。Laravel用戶可以按照評論,類別,發佈等

這是我試過的。

用戶模型

public function categories() 
{ 
    return $this->morphedByMany(Category::class, 'followable', 'follows')->withTimestamps(); 
} 

分類模式

public function followers() 
{ 
    return $this->morphMany(Follow::class, 'followable'); 
} 

後續型號

public function followable() 
{ 
    return $this->morphTo(); 
} 

public function user() 
{ 
    return $this->belongsTo(User::class); 
} 

按遷移

Schema::create('follows', function (Blueprint $table) { 
    $table->bigIncrements('id'); 
    $table->unsignedBigInteger('user_id'); 
    $table->morphs('followable'); 
    $table->timestamps(); 
}); 

我怎樣才能獲得所有categoriescomments其次是用戶。我怎麼能得到一個Cateogry或Commnets等追隨者

請幫助。

回答

1

你不需要Follow模型。
所有你需要的是數據透視表,像這樣

followable 
    user_id - integer 
    followable_id - integer 
    followable_type - string 

添加folowers方法所有的類,你需要遵循

例如
分類模式

public function followers() 
{ 
    return $this->morphToMany(User::class, 'followable'); 
} 

然後在用戶型號

public function followers() 
{ 
    return $this->morphToMany(User::class, 'followable'); 
} 

public function followedCategories() 
{ 
    return $this->morphedByMany(Category::class, 'followable')->withTimestamps(); 
} 

public function followedComments() 
{ 
    return $this->morphedByMany(Comment::class, 'followable')->withTimestamps(); 
} 

public function followedPosts() 
{ 
    return $this->morphedByMany(Post::class, 'followable')->withTimestamps(); 
} 

// and etc 

public function followedStuff() 
{ 
    return $this->followedCategories 
     ->merge($this->followedComments) 
     ->merge($this->followedPosts); 
} 

然後,你可以通過訪問特定的類別,評論或張貼或任何你想的追隨者達到你的目標(如果它隨動courcse的)
例如:

$folowers = $category->folowers; 
// will return all followers this category 
$all = $user->followedStuff(); 
// will return collection of all things followable by the user 
+0

還有一兩件事,我可以通過'$ user-> followers'獲得用戶關注者關於用戶關注的內容,如何讓所有用戶關注用戶。 – Saqueib

相關問題