简体   繁体   中英

Laravel belongsToMany with OR condition

How do I create brackets around my orWhere:

public function categories()
{
    return $this->belongsToMany('App\Category', 'user_category')->orWhere('default', 1);
}

So it is converted to this:

where (`user_category`.`user_id` = ? or `default` = 1) 

Currently the brackets here are missing and mess up the whole query. I tried for example:

public function categories()
{
    $join = $this->belongsToMany('App\Category', 'user_category')
      ->orWhere('default', 1);
    return $this->where(function ($query) use ($join) {
        return $join;
    });
}

But here I am loosing my model and getting Call to undefined method Illuminate\\Database\\Query\\Builder::...

You can use advanced where clause like:

Model::where(function ($query) {
    $query->where('a', '=', 1)
          ->orWhere('b', '=', 1);
})->where(function ($query) {
    $query->where('c', '=', 1)
          ->orWhere('d', '=', 1);
});

Or nested clause like :

Model::where(function($query)
{
    $query->where('a', 'like', 'keyword');
    $query->or_where('b', 'like', 'keyword');
})
->where('c', '=', '1');

Are you trying to get all the categories related to an user and the categories where the default field is 1?

If that is the case:

public function categories()
{
    return $this->belongsToMany('App\Category');
}

public function relatedCategories()
{
    return App\Category::all()->where('default',1)->merge($this->categories);
}

The relatedCategories() method should return a collection with the desired categories. Take in care that the non-related categories but with default=1 will not have the pivot object, because these categories doesn't exist in your pivot table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM