如何在Laravel 5.2中使用这个MySQL查询?

3
我想将以下SQL查询语句用于Laravel 5.2。
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中使用?任何帮助都将不胜感激。

谢谢

1个回答

4
如果你只需要基本的查询,你可以使用DB::raw函数(文档)。
select(DB::raw('SELECT * FROM products WHERE soundex(products.name)=soundex("Neckholder Creme")'));

或者你可以在Eloquent中使用whereRaw,并将其用于现有的查询中(文档)。

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);

希望能帮到您


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接