문제

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