php - 对具有最多相似标签的帖子进行排序

标签 php mysql laravel

我知道以下代码可以选择 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/

相关文章:

javascript - 如何从 Blade 模板中的 Javascript 文件重定向 Laravel 路由

php - 如何在 cakephp 2.x 中发送 410

mysql - 与 '<server name>:<port>' 处的 MySQL 服务器失去连接,系统错误 : 10053 An established connection was aborted

javascript - 执行mysql查询后刷新图表(javascript)

php - 错误方法 Illuminate\\Database\\Eloquent\\Collection::save 不存在。在 Laravel

laravel - 在 Laravel 模型中定义表名

Laravel Scout 配置 AWS elasticSearch 服务

php - 让3人从sql中获得更高的值(value)

php - 打印出一个对象类型的 PHP 数组

mysql - 将sql文件导入MySQL