2017-02-10 108 views
2

我想下面的SQL查詢中使用到laravel 5.2我怎樣才能使用這個MySQL查詢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中使用?任何幫助將不勝感激。

感謝

回答

2

如果你只需要基本的查詢,那麼你可以使用DB::rawdocumentation

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

或者你可以用雄辯使用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); 

希望它有幫助