我知道以下代码可以选择Post模型中具有ID:1,2,3至少具有标签之一的每个帖子
void initializeCard(int row[5], int min, int max, int i)
{
row[i] = rand() % ((max + 1) - min) + min;
int temp;
for (temp = i-1; temp >= 0; temp--) //Do not check i itself
{
if (row[i] == row[temp])
{
initializeCard(row, min, max, i);
return; //No need to continue this function
}
}
i++; //Increment before checking, otherwise it is executed with i=5 which is out of bounds
if (i < 5)
{
initializeCard(row, min, max, i);
}
}
输出:
$ids = [1,2,3];
$posts = Post::with('tags')->whereHas('tags', function ($query) use ($ids) {
$query = $query->whereIn('id', $ids);
})->get();
现在,我的问题是如何对具有最多类似标签的帖子进行排序。我的意思是,在$ ids中具有更多类似标签的帖子具有更高的优先级,首先是具有所有3个标签,然后具有2个标签,最后是我列表中的1个标签的帖子?
答案 0 :(得分:0)
$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());