sql - 存在查询不返回相关结果
问题描述
我有一个带有这个 Eloquent 查询的 Laravel 应用程序:
$products = Product::where('name', 'LIKE', "%{$value}%")
->whereHas('categories', function($q) {
$q->where( 'slug', 'tonery-cartridge' );
})->with('manufacturer')
->with('sm_image')
->orderBy('created_at','DESC')
->take(10)
->get();
此代码生成如下 sql 命令:
select * from `products` where `name` LIKE '%can%'
and exists (
select * from `categories` inner join `category_product`
on `categories`.`id` = `category_product`.`category_id`
where `products`.`id` = `category_product`.`product_id`
and `slug` = 'tonery-cartridge'
)
order by `created_at` desc limit 10
我确信有些产品的名称包含“can”字符串,并且属于带有 slug“tonery-cartridge”的类别。为什么这个查询返回一个空结果?如果我尝试inner join
手动创建 sql,它的效果很好,如下面的屏幕截图所示:
解决方案
我认为您的查询不等效。laravel的SQL
输出不会在它的FROM
子句中连接表,但是在您手动构建的SQL
语句中,您会在子句中进行很多内部连接,FROM
并在结果表上执行您的操作,而前者并非如此。
尝试以下
DB::table('products')
->join('category_product', 'category_product.product_id', '=', 'products.id')
->join('categories', 'category_product.category_id', '=', 'categories.id')
->whereRaw('products.name LIKE %can% AND categories.slug = "tonery-cartridge"')
->select('products.name', 'categories.slug')
->orderBy('created_at','DESC')
->take(10)
->get()
如果您想避免使用whereRaw
,可以尝试以下方法。
DB::table('products')
->join('category_product', 'category_product.product_id', '=', 'products.id')
->join('categories', 'category_product.category_id', '=', 'categories.id')
->where([
['products.name, 'LIKE', '%' . $value . '%'],
['categories.slug', '=', 'tonery-cartridge']])
->select('products.name', 'categories.slug')
->orderBy('created_at','DESC')
->take(10)
->get()
高温高压
推荐阅读
- flutter - Flutter & Dart:如何检查/知道哪个类调用了函数?
- python - 用 Panda 构建奇数行的矩阵
- c++ - error c2679 binary '=' no operator found which takes right hand operand of type std::tuple
- angular - How to display real time data thorugh Angular data table?
- python - TypeError: read_excel() got an unexpected keyword argument 'keep_date_col'
- rust - 测试在工作区中的行为与作为独立项目不同
- asp.net - 无法序列化会话状态“System.Web.SessionState.HttpSessionState”
- c++ - GCC C++ 链接错误:未定义对“WinMain@16”的引用
- telephony - 在 Bitrix24 中收听代理的呼叫
- c++ - 在 QT 中以(快速)恒定速率旋转 3D 对象