【发布时间】:2021-10-20 09:39:46
【问题描述】:
获取此工作代码。它首先在users 表中搜索关键字,然后使用whereHas() 方法在透视表category_user 中搜索分配给给定类别的任何用户。这很好用,检索到所有条目。
所以绝对清楚 3 个表正在使用中,users、categories 和 category_user。
我正在使用 Laravel 集合 sortByDesc() 根据相关性对条目进行排序。因此,如果 category 1、category 2 和 my example search term 的关键字都针对 user 1 存储,并且仅针对 user 2 存储了 category 1,user 1 将首先显示在结果中。
下面的代码正是这样做的,但 ONLY 在users 表上。由于我需要订购的方式的独特性,我已经进行了很好的扫描,并且似乎无法将此解决方案应用于此类查询。任何人都可以提供任何方法吗?
//props for sortByDesc
$props = ['name', 'slug', 'location', 'company_name', 'biography', 'usually_active'];
//Search Query
//1. Search users table for keywords
//2. use whereHas() to search pivot table of categories for keyword and filters selected
//3. use sortByDesc collections to order results based number of matches, most matches ordered at the top
$search_results = User::where('approved', '=', 1)
->where('user_type_id', '=', 1)
->orWhere(function ($q) use ($search_items) {
//search users tables
foreach ($search_items as $value) {
$q->orWhere('name', 'like', "%{$value}%");
$q->orWhere('location', 'like', "%{$value}%");
$q->orWhere('company_name', 'like', "%{$value}%");
$q->orWhere('biography', 'like', "%{$value}%");
$q->orWhere('usually_active', 'like', "%{$value}%");
}
})->whereHas('categories', function ($q) use($search_items) {
//search categories table
if(!empty($search_items)):
$q->whereIn('name', $search_items);
$q->orWhereIn('slug', $search_items);
endif;
//Now we sort based on best matches
})->get()->sortByDesc(function($i, $k) use ($search_items, $props) {
// The bigger the weight, the higher the record
$weight = 0;
// Iterate through search terms
foreach($search_items as $item) {
foreach($props as $prop) {
if(strpos($i->{$prop}, $item) !== false)
$weight += 1; // Increase weight if the search term is found
}
}
return $weight;
});
//get the results and paginate
$search_results = $search_results->values()->all();
$search_results = $this->paginate($search_results);
【问题讨论】: