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