Is there any way to use closure for where
in join clause in Eloquent?
What I'm trying to do is:
$model = $model->leftJoin('history', function ($join) {
$join->on('history.record_id', '=', 'work_order.work_order_id');
$join->where('history.tablename', '=', 'test');
$join->where('history.columnname', '=', 'column');
$join->where(function ($q) {
$q->where('history.value_from', '=', '0')
->orWhere('history.value_from', '=', '');
});
$join->where('history.value_to', '>', '0');
});
but obviously the part:
$join->where(function ($q) {
$q->where('history.value_from', '=', '0')
->orWhere('history.value_from', '=', '');
});
doesn't work because JoinClause
doesn't support closure for where
The method you are looking for is called whereNested
and is available from the Illumintate\Database\Query\Builder
class.
Unfortunately, the $join
parameter passed to the join closure is of type Illumintate\Database\Query\JoinClause
which only has 4 methods for handling where statements for the join where
, orWhere
, whereNull
and whereNotNull
.
To make this work you'll need to resort to using DB::raw
. This should work:
$model = $model->leftJoin('history', function ($join) {
$join->on('history.record_id', '=', 'work_order.work_order_id');
$join->where('history.tablename', '=', 'test');
$join->where('history.columnname', '=', 'column');
$join->where(DB::raw('(`history`.`value_from` = 0 or `history`.`value_from` = "")'), '', '');
$join->where('history.value_to', '>', '0');
});