Use a join
Oct 12, 2023
5
Level 1
Order by relation found in field
Hello community. I have issue with query ordering. At first sight it is very simple, but I have no idea how can I solve it.
I have eloquent query like this:
Product::query()
->published()
->whereHas('translations', function($query) {
$query
->whereIn('key', ['short_name', 'short_description', 'category_description'])
->where('content', 'like', '%some_search_request%')
})
->whereHas('page_info', function($query) {
$query
->where('title', 'like', '%some_search_request%')
->orWhere('h1', 'like', '%some_search_request%')
->orWhere('description', 'like', '%some_search_request%')
})
->paginate(20);
This query is used for search and live search on website. That is why we need to show most relevant items firstly.
Task, we need to order in such way:
- Firstly show items if we found match in relation 'translation' and keys 'short_name' or 'short_description'
- Secondarily if we have match in relation 'translation' and key 'category_description'
- Thirdly if we have match in relation 'page_info' in any column.
Does anyone have any idea?
Level 6
@jordan-dev let's do it with a little db raw (only if you want it) 🤣🤣
try this
Product::query()
->published()
->select(['products.*', DB::raw('
CASE
WHEN translations.key IN ("short_name", "short_description") AND translations.content LIKE "%some_search_request%" THEN 1
WHEN translations.key = "category_description" AND translations.content LIKE "%some_search_request%" THEN 2
WHEN page_info.title LIKE "%some_search_request%" OR page_info.h1 LIKE "%some_search_request%" OR page_info.description LIKE "%some_search_request%" THEN 3
ELSE 4
END AS priority
')])
->join('translations', 'products.id', '=', 'translations.product_id')
->leftJoin('page_info', 'products.id', '=', 'page_info.product_id')
->where(function($query) {
$query->whereIn('translations.key', ['short_name', 'short_description', 'category_description'])
->where('translations.content', 'like', '%some_search_request%')
->orWhere('page_info.title', 'like', '%some_search_request%')
->orWhere('page_info.h1', 'like', '%some_search_request%')
->orWhere('page_info.description', 'like', '%some_search_request%');
})
->orderBy('priority')
->paginate(20);
Please or to participate in this conversation.