我在我的網站中創建了搜索功能。不過,我的舊查詢引入了deleted_at列,儘管它們爲空。Laravel查詢生成器中的複雜查詢
所以我寫了原始MySQL的查詢,並得到我期待的結果。
但是,我正在努力使用Laravel的查詢生成器來寫這個。工作MySQL查詢我想的是:
select * from `packs`
left join `keywords`
on `keywords`.`pack_id` = `packs`.`pack_id`
inner join `categories`
on `categories`.`category_id` = `packs`.`primary_category_id`
left join `ratings`
on `ratings`.`pack_id` = `packs`.`pack_id`
where (`pack_title` LIKE '%sams%'
or `keywords`.`keyword_title` LIKE '%sams%')
and `packs`.deleted_at is null
group by `pack_title`
order by `packs`.`created_at`
desc
我使用Laravel當前的嘗試看起來像這樣:
// Explode Terms
$terms = explode(' ', $q);
// Produce Query (Initially)
$query = DB::table('packs')
->leftJoin('keywords', 'keywords.pack_id', '=', 'packs.pack_id')
->leftJoin('categories', 'categories.category_id', '=', 'packs.primary_category_id')
->whereNotNull('packs.deleted_at')
->leftJoin('ratings', 'ratings.pack_id', '=', 'packs.pack_id');
// Loop through each term
foreach($terms as $term)
{
$query->where('pack_title', 'LIKE', '%'. $term . '%')
->orWhere(function($query, $term)
{
$query->orWhere('pack_description', 'LIKE', '%'. $term . '%')
->orWhere('keywords.keyword_title', 'LIKE', '%'. $term . '%');
})
->whereNotNull('packs.deleted_at')
->groupBy('pack_title')
->orderBy('packs.created_at', 'DESC');
}
// Log
Log::info('User Searched using term : '.$q.'');
$results = $query->get();
這是產生錯誤:
缺少論據2 SearchesController :: {closure}()
這是可以寫查詢構建呃,如果是這樣的話。如果需要,我不介意將它編寫爲RAW查詢。
感謝
嘗試'函數($查詢)使用($項)'代替'函數($所作的更改查詢,$ term)' –