Laravel查询生成器中的复杂查询

时间:2015-11-26 08:50:57

标签: php mysql laravel-4

我在我的网站中创建了一个搜索功能。但是我的旧查询引入了deleted_at列,尽管它们是null。

所以我在原始MySQL中编写了查询,并得到了我期待的结果。

但是,我正在努力使用Laravel的Query Builder实际编写它。我喜欢的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();

这产生错误:

  

SearchesController :: {closure}()

缺少参数2

这是否可以在Query Builder中编写,如果是这样的话。我不介意在需要的时候探索将其写为RAW查询。

由于

1 个答案:

答案 0 :(得分:1)

试试这个:

$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) use ($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();

注意:我在此处进行了更改->orWhere(function($query) use ($term)