Chessler
Chessler

Reputation: 117

Excluding pivot rows in Eloquent ORM query

(laravel 4.2)

There are four tables involved; users, posts, flags, and post_flags.

I want to retrieve every post a certain user has, and retrieve the flags set for the post, but only the flags that are set by the user in question.

For example: A post can have flags: 1,2,2,3 where flag 2 is set twice. Once by User A, once by User B. I don't want to see the flags that User B has set.

The Eloquent query in my controller:

$posts = Post::whereHas('companies', function($q) use($company_id) {
        $q->where('id', '=', $company_id);
    })->with('flags')->get();

The Relation in my Post model:

public function flags() {
    return $this->belongsToMany('PostFlag', 'post_postflags', 'post_id', 'flag_id')
    ->withTimestamps()->withPivot('owner');
}

How would I achieve this using Eloquent ORM?

UPDATE

My final query, thanks to andrewtweber:

Final query

$posts = Post::whereHas('users', function($q) use($id) {
            $q->where('id', '=', $id);
         })->get()->load([
            'flags' => function($query) use($id) {
                $query->where('owner', '=', $id)->orWhere('owner', '=', 'SYSTEM');
            }
         ]);

Upvotes: 1

Views: 224

Answers (1)

andrewtweber
andrewtweber

Reputation: 25559

Use wherePivot

http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Relations/MorphToMany.html

$flags = $post->flags()
    ->wherePivot('user_id', '=', $user_id)
    ->get();

Or with eager loading

$posts->load([
    'flags' => function ($query) use($user_id) {
        $query->wherePivot('user_id', '=', $user_id);
    }
]);

Upvotes: 1

Related Questions