我正在公告网站上使用高级搜索引擎。我必须在某个时候使用orderByRaw
,因为我需要以复杂的方式订购。问题是它从字面上删除了部分SQL,我不知道如何解决这个问题。
使用链接的查询
$announcements = Announcement::select('announcements.*')
->getOnline()
->withCitySlug($location)
->withCategory($category_id)
->orderByResearchPageOption()
->get();
这里是模型Announcement
本身的有趣部分
public function scopeOrderByResearchPageOption() {
return $this->leftJoin('announcement_options', 'announcements.id', '=', 'announcement_options.announcement_id')
->orderByRaw('CASE
WHEN announcement_options.option_slug = "research_page" then 1
WHEN announcement_options.option_slug = "" then 2
ELSE 3 END')
->select('announcements.*'); // to avoid leftJoin bullshit
}
public function scopeGetOnline($query) {
return $query->where('status', '=', 'online');
}
public function scopeWithCitySlug($query, $city_slug) {
if (empty($city_slug)) return $query;
return $query->where('city_slug', 'LIKE', '%'.$city_slug.'%');
}
public function scopeWithCategory($query, $category_id) {
if ($category_id === FALSE) return $query;
return $query->join('announcement_categories', 'announcement_categories.announcement_id', '=', 'announcements.id')
->join('categories', 'categories.id', '=', 'announcement_categories.category_id')
->where('categories.id', '=', $category_id);
}
当我删除查询的orderByResearchPageOption()
时,原始SQL是
array(3) { ["query"]=> string(284) "select `announcements`.* from `announcements` inner join `announcement_categories` on `announcement_categories`.`announcement_id` = `announcements`.`id` inner join `categories` on `categories`.`id` = `announcement_categories`.`category_id` where `status` = ? and `categories`.`id` = ?" ["bindings"]=> array(2) { [0]=> string(6) "online" [1]=> int(11) } ["time"]=> float(1.88) }
它可以完美地工作,但是当我添加它时,它会改变整个查询,我们会丢失绑定逻辑等。
array(3) { ["query"]=> string(375) "select `announcements`.* from `announcements` left join `announcement_options` on `announcements`.`id` = `announcement_options`.`announcement_id` order by CASE WHEN announcement_options.option_slug = "research_page" then 1 WHEN announcement_options.option_slug = "" then 2 ELSE 3 END" ["bindings"]=> array(0) { } ["time"]=> float(16.12) }
有人知道该怎么做吗?我真的输了,我无法避免这个项目的orderByRaw
,我搜索了很多...
另一个想法是在原始SQL中转换所有内容,但它真的不灵活,我更喜欢这种方式:(
谢谢;)
答案 0 :(得分:0)
最后这是一个愚蠢的错误,对于任何会遇到类似问题的人来说,不要忘记用当前的`{/ p>替换$this
public function scopeOrderByResearchPageOption($query) {
return $query->leftJoin('announcement_options', 'announcements.id', '=', 'announcement_options.announcement_id')
->orderByRaw('CASE
WHEN announcement_options.option_slug = "research_page" then 1
WHEN announcement_options.option_slug = "" then 2
ELSE 3 END')
->select('announcements.*'); // to avoid leftJoin bullshit
}