【问题标题】:How can I use this mysql query to laravel 5.2?如何将此 mysql 查询用于 laravel 5.2?
【发布时间】:2017-02-10 16:41:41
【问题描述】:

我想在 laravel 5.2 中使用下面的 sql 查询

SELECT * FROM `products` WHERE soundex(`products`.`name`)=soundex('Neckholder Creme');

我在这里试过

return $query->select([ 'products.slug', 'products.id', 'sku', 'name', 'regular_price', 'sale_price', 'sale_from', 'sale_to', 'stock_status', 'product_type', 'featured_image_id' ])
            ->with('media_featured_image')
            ->with('categories')
            ->where('products.product_type', '<>', 'variation')
            ->where('products.status',  'publish')
            ->where(function($query) use ($keyword){
                foreach($keyword as $k){
                    $query->where('soundex(products.name)',soundex($k));
                }
            })
            ->paginate(120);

但它给出了如下所示的错误,并且由于列名中的``而出现问题

Column not found: 1054 Unknown column 'soundex(products.name)' in 'where clause' (SQL: select count(*) as aggregate from `products` where exists (select * from `categories` inner join `category_product` on `categories`.`id` = `category_product`.`category_id` where `category_product`.`product_id` = `products`.`id` and `categories`.`slug` <> shoparchiv) and `products`.`product_type` <> variation and `products`.`status` = publish and (`soundex(products`.`name)` = C352 and `soundex(products`.`name)` = J520))

如何在 Laravel 中使用?任何帮助将不胜感激。

谢谢

【问题讨论】:

    标签: laravel laravel-5.2


    【解决方案1】:

    如果您只需要基本查询,则可以使用DB::raw (documentation)

    select(DB::raw('SELECT * FROM products WHERE soundex(products.name)=soundex("Neckholder Creme")'));
    

    或者您可以在 eloquent 中使用 whereRaw 并在您现有的查询中使用它 (documentaion)

    return $query->select([ 'products.slug', 'products.id', 'sku', 'name', 'regular_price', 'sale_price', 'sale_from', 'sale_to', 'stock_status', 'product_type', 'featured_image_id' ])
                ->with('media_featured_image')
                ->with('categories')
                ->where('products.product_type', '<>', 'variation')
                ->where('products.status',  'publish')
                ->where(function($query) use ($keyword){
                    foreach($keyword as $k){
                        $query->whereRaw("soundex(products.name) = '".soundex($k)."'");
                    }
                })
                ->paginate(120);
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-26
      • 2017-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多