我知道以下代码可以选择 Post 模型中至少具有 id:1,2,3 标签之一的每个帖子
$ids = [1,2,3];
$posts = Post::with('tags')->whereHas('tags', function ($query) use ($ids) {
$query = $query->whereIn('id', $ids);
})->get();
输出:
Collection {
#items: array:3 [
0 => Post {
...
#attributes: array: [
'id' => 1,
'title' => 'title',
'content' => 'content'
]
...
#relations: array:1 [▼
"tags" => Collection {#828 ▼
#items: array:3 [▼
0 => Tag {#806 ▶}
1 => Tag {#807 ▶}
2 => Tag {#808 ▶}
]
}
]
...
现在,我的问题是如何对具有最多相似标签的帖子进行排序。我的意思是,在我的 $ids 中具有更多相似标签的帖子具有更高的优先级,首先是具有所有 3 个标签的帖子,然后是我列表中的 2 个标签,最后是 1 个标签?
最佳答案
$collection = collect([
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);
$sorted = $collection->sortBy(function ($product, $key) {
return count($product['colors']);
});
dd($sorted->values()->all());
关于php - 对具有最多相似标签的帖子进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53424762/