xiolog's avatar

Using where and orWhere

Hi all. I have a problem.

I have a table "saunas" in a database that contains two columns: "station" and "busstation". Each of these columns can have values: empty, null or string.

Each sauna belongs to a certain city. As a result, there are 96 saunas in a particular city.

I want to write an Eloquent query in which I want to select rows in which there are non-empty fields "station" and/or "busstation".

If I just do a "where" query on the "station" field, it works fine. It outputs 54 saunas.

If I do an additional query orWhere in the field "busstation", it outputs all the saunas that are in the database. And there are more than 5000 of them.

What is my mistake?

My relation in the model City.php:

/**
* @return HasMany
*/
public function saunas(): HasMany
{
    return $this->hasMany(Sauna::class);
}
     	

My controller SaunasController.php

public function show(City $city)
{
    $stations = $city->saunas()
        ->where(function($query) {
            $query->where('station', '<>', '')->whereNotNull('station');
        })
         ->orWhere(function($query) {
            $query->where('busstation', '<>', '')->whereNotNull('busstation');
        })
        ->get(['city_id', 'title', 'station', 'busstation']);
}
0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

There is an implied where('city_id', $city) whenever you use the relationship, so you need to logically group the OR where :

 $stations = $city->saunas()->where(function ($builder) {
    $builder->where(function($query) {
        $query->where('station', '<>', '')->whereNotNull('station');
    })
    ->orWhere(function($query) {
        $query->where('busstation', '<>', '')->whereNotNull('busstation');
    })
})->get(['city_id', 'title', 'station', 'busstation']);
1 like
xiolog's avatar

The solution was easy. Thank you very much! :)

Please or to participate in this conversation.