2013-12-11 59 views
1

我執行關係,口才很好,我面臨着以下問題時:檢查一個多對多的關係,上市資源

article可以有很多followers(用戶),和user可以按照很多articles(按照我的意思,用戶在更新後續文章時會收到通知)。

定義這種關係很簡單:

class User extends Eloquent { 

    public function followedArticles() 
    { 
     return $this->belongsToMany('Article', 'article_followers'); 
    } 

} 

class Article extends Eloquent { 

    public function followers() 
    { 
     return $this->belongsToMany('User', 'article_followers'); 
    } 

} 

現在,列出我想要顯示每個物品的額外信息的文章時:如果當前用戶是或不是跟着它。

因此,對於每一篇文章我將有:

  • article_id
  • title
  • content
  • etc.
  • is_following(附加域)

我現在正在做的是這樣的:

$articles = Article::with(array(
       'followers' => function($query) use ($userId) { 
        $query->where('article_followers.user_id', '=', $userId); 
       } 
      ) 
     ); 

這樣,我對每一篇文章的額外字段:「包含與單個用戶的數組followers`,如果用戶下面的文章,或者一個空數組如果他沒有跟蹤它。

在我的控制器中,我可以處理這些數據以獲得我想要的形式,但是我感覺這是一種破解。

我很想有一個簡單的is_following字段與boolean(無論用戶是否在文章中)。

有沒有簡單的方法來做到這一點?

回答

0

這樣做將是創建自定義字段的訪問的方法之一:

class Article extends Eloquent { 
    protected $appends = array('is_following'); 
    public function followers() 
    { 
     return $this->belongsToMany('User', 'article_followers'); 
    } 
    public function getIsFollowingAttribute() { 
     // Insert code here to determine if the 
     // current instance is related to the current user 
    } 
} 

這是什麼會做的是創建一個名爲「is_following」新的領域,它會自動被添加到返回的JSON對象或型號。

確定當前登錄用戶是否在文章後面的代碼將取決於您的應用程序。 像這樣的東西應該工作:

return $this->followers()->contains($user->id);