首页 > 解决方案 > 存在查询不返回相关结果

问题描述

我有一个带有这个 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,它的效果很好,如下面的屏幕截图所示:

phpMyAdmin 截图

标签: sqllaraveleloquent

解决方案


我认为您的查询不等效。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()

高温高压


推荐阅读