Hi guys,
Is it possible to create a where clause which first attempts to find a row matching a client_id, and when non is found performs a orWhereNull?
Below is the query i am currently working with, on line two i initiate a where statement which should do the above, however currently it retreives both the row with and without a client_id.
$q = Cns::with(['rates' => function ($a) use ($client) {
$a->where(function($b) use ($client) {
$b->where('client_id', $client->id)
->orWhereNull('client_id');
});
$a->whereNull('subordinates');
$a->where(function($b) {
$b->where('valid_from', '<=', Carbon::now()->format('Y-m-d'))
->orWhereNull('valid_from');
});
$a->orderBy('cns_id', 'asc');
$a->orderBy('valid_from', 'desc');
}])->with(['futureRates' => function ($a) use ($client) {
$a->where('client_id', $client->id);
$a->whereNull('subordinates');
$a->where('valid_from', '>', Carbon::now()->format('Y-m-d'));
$a->orderBy('cns_id', 'asc');
$a->orderBy('valid_from', 'desc');
}])
->where('descript', 'like', '%'. $country->name .'%');
The table structure for the 'rates' table looks like this:
id, cns_id, client_id, subordinates, etc., etc.
-------------------------------------------------
1, 6, 3, null, etc., etc.
2, 6, 5, null, etc., etc.
3, 6, 7, null, etc., etc.
4, 6, null, null, etc., etc.
This would be an example of what the query should do: cns_id=6 AND client_id=3 , if there is no client_id with 3 found, than take the row with cns_id=3 AND client_id is null