سؤال

I need to fetch all models which a user belongs to and additionally all models where private = 0 (From all other users)

I already tried it with two merged seperate queries - but with this method there are duplicated items.

Also this approach doesn't work:

$this->belongsToMany('ManiacTwister\Models\Collection', 'collection_members')
->orWhere("private", "=", 0);
هل كانت مفيدة؟

المحلول

Assuming the 'private' field is on your collection_members table then setup a pivot field using 'private' and then search by the pivot

$this->belongsToMany('ManiacTwister\Models\Collection', 'collection_members')
        ->orWherePivot('private','0');

or you could

$this->belongsToMany('ManiacTwister\Models\Collection', 'collection_members')
       ->orWhere("collection_members.private", "=", 0);

Both should work the first one is table agnostic (i.e. it links to the model) but the second one will be faster

نصائح أخرى

Take off the orWhere() on your model and eager load it.

$member = Member::where('id', '1')->has(array('collections' => function($q)
{
    $q->where('private', '0');
}))->get()->first();

foreach($member->collections as $collection) {
     echo $collection->name;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top