当 DataTables 尝试获取数据时,它总是会遇到这个 Eloquent 查询:
$items = Item::select([
DB::raw("images.url AS image"),
'items.id',
'items.sku',
'items.quantity',
DB::raw("IF(items.enabled, 'Yes', 'No') AS enabled")
])
->leftJoin('images', function ($j) {
$j->on('images.imageable_id', '=', 'items.id')
->where('images.imageable_type', '=', 'Item');
})
->leftJoin('order_items', 'items.id', '=', 'order_items.item_id')
->leftJoin('orders', 'orders.id', '=', 'order_items.order_id')
->where('items.store_id', 1)
->whereNull('items.deleted_at')
->whereIn('items.status', ['active', 'submitted'])
->groupBy('items.id');
查询按原样正常工作并返回所需的结果。但是,DataTables 尝试将其转换为以下内容,这会产生错误:
select count(*) as aggregate from (select '1' as row from `items` left join `images` on `images`.`imageable_id` = `items`.`id` and `images`.`imageable_type` = 1 left join `order_items` on `items`.`id` = `order_items`.`item_id` left join `orders` on `orders`.`id` = `order_items`.`order_id` where `items`.`store_id` = 1 and `items`.`deleted_at` is null group by `items`.`id`) AS count_row_table
这会具体产生此错误:
SQLSTATE[HY093]: Invalid parameter number
/home/vagrant/Projects/test.dev/vendor/laravel/framework/src/Illuminate/Database/Connection.php#301
当我直接在MySQL数据库上执行该查询时,没有问题。这似乎只发生在 Laravel 中。
如果我删除查询的 ->leftJoin('images', function ($j) {...}
部分,则不会出现错误,但我需要图像的连接.
如何解决此错误?
通过 AJAX 返回到 DataTables 的完整错误输出:
{
"error":{
"type":"Illuminate\\Database\\QueryException",
"message":"SQLSTATE[HY093]: Invalid parameter number (SQL: select count(*) as aggregate from (select '1' as row from `items` left join `images` on `images`.`imageable_id` = `items`.`id` and `images`.`imageable_type` = 1 left join `order_items` on `items`.`id` = `order_items`.`item_id` left join `orders` on `orders`.`id` = `order_items`.`order_id` where `items`.`store_id` = active and `items`.`deleted_at` is null and `items`.`status` in (submitted, ?) group by `items`.`id`) AS count_row_table)",
"file":"\/home\/vagrant\/Projects\/test.dev\/vendor\/laravel\/framework\/src\/Illuminate\/Database\/Connection.php",
"line":625
}
}
最佳答案
我今天遇到了类似的问题,不是 DataTables 的问题,而是使用独立查询生成器构建的复杂查询的问题。该问题与左连接的问题类似,通过闭包来构建更复杂的连接条件。我在“on”之后使用了where条件。
解决方案是链接“on”调用:
->leftJoin('images', function ($j) {
$j->on('images.imageable_id', '=', 'items.id')
// note the "on" rather than the "where" and the use of a raw statement
->on('images.imageable_type', '=', DB::raw('Item'));
})
关于mysql - 在 Laravel 中使用 DataTables 时出现无效参数编号错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28095782/