Php 雄辩的连接-何处闭合

Php 雄辩的连接-何处闭合,php,laravel,eloquent,laravel-5,query-builder,Php,Laravel,Eloquent,Laravel 5,Query Builder,有没有办法在Eloquent中的join子句中对where使用闭包 我想做的是: $model = $model->leftJoin('history', function ($join) { $join->on('history.record_id', '=', 'work_order.work_order_id'); $join->where('history.tablename', '=', 'test')

有没有办法在Eloquent中的join子句中对
where
使用闭包

我想做的是:

 $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');
            });
但显然,这一部分:

$join->where(function ($q) {
     $q->where('history.value_from', '=', '0')
       ->orWhere('history.value_from', '=', '');
});

不起作用,因为
JoinClause
不支持where

的闭包。您要查找的方法称为
whereNested
,可从
Illumintate\Database\Query\Builder
类获得

不幸的是,传递给连接闭包的
$join
参数的类型为
Illumintate\Database\Query\JoinClause
,它只有4种方法来处理连接的where语句
where
或where
whereNull

要实现这一点,您需要使用
DB::raw
。这应该起作用:

$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');
            });

你为什么要在那里用闭包?您试图用它生成什么查询?它是where子查询还是像这样将where语句组合在一起:
。。。和(history.value\u-from=0或history.value\u-from=“”)…
?@Bogdan我想使用类似这样的东西
SELECT*from-work\u-order LEFT在history.record\u-id=work\u-order.work\u-order\u-id和history.tablename='test'和history.columnname='column',(history.value\u-from=0或history\u-value\u-from='')历史值为>0…
代替
(在末尾)可以是其他联接或WHERE子句。目前,作为解决方法,我已经为此查询创建了关系,但这样运行2个查询而不是一个查询。这里有一个可能的(黑客)解决方法:。它似乎不是这样工作的。我发现:
哎呀,好像出了什么问题。Connection.php第614行中的2/2 QueryException:SQLSTATE[42000]:语法错误或访问冲突:1064您的SQL语法有错误;检查与您的MySQL服务器版本对应的手册,以了解使用接近“”的正确语法?和
history
value\u to`>?其中
工单
工单id
=?在第1行
处限制1'。这可能是绑定的问题。当我删除这个
where`with
DB::raw
时,它工作正常。奇怪的是,此错误后显示的查询看起来很好。请尝试对第二个和第三个参数使用
DB::raw(“”)
,以避免引用不应使用的值。如下所示:
$join->where(DB::raw('(history.value_from=0或history.value_from=“”)),DB::raw(“”),DB::raw(“”)。不幸的是,它没有更改错误。查询仍然无法运行。这在各种方面都很奇怪。我已经复制了您的代码并通过调试器运行了它。这里的异常是在调用
prepare
方法时由PDO引发的。但是,如果我手动设置PDO连接并尝试相同的步骤:
new PDO(…)
prepare($query)
execute($bindings)
,使用由Eloquent构建的完全相同的值,它就可以正常工作。