列出资源时检查多对多关系

I'm implementing relationships in Eloquent, and I'm facing the following problem:

An article can have many followers (users), and a user can follow many articles (by follow I mean, the users get notifications when a followed article is updated).

Defining such a relationship is easy:

class User extends Eloquent {

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

}

also

class Article extends Eloquent {

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

}

Now, when listing articles I want to show an extra information about each article: if the current user is or is not following it.

So for each article I would have:

  • article_id
  • title
  • content
  • etc.
  • is_following (extra field)

What I am doing now is this:

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

This way I have an extra field for each article: 'followers` containing an array with a single user, if the user is following the article, or an empty array if he is not following it.

In my controller I can process this data to have the form I want, but I feel this kind of a hack.

I would love to have a simple is_following field with a boolean (whether the user following the article).

Is there a simple way of doing this?

One way of doing this would be to create an accessor for the custom field:

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
    }
}

What this will do is create a new field named 'is_following' which will automatically be added to the returned json object or model.

The code to determine whether or not the currently logged in user is following the article would depend upon your application. Something like this should work:

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