【问题标题】:Laravel posts types categoriesLaravel 帖子类型类别
【发布时间】:2020-12-18 15:08:12
【问题描述】:

我需要一个包含类别的数组,每个类别有 4 个帖子:一个包含两个类型为 1 的帖子的数组和一个包含两个类型为 2 的帖子的数组。没有 type_3。

显示应该是这样的(不使用刀片):

category name_1

    post type_1 name
    post type_1 name

    post type_2 name
    post type_2 name

category name_2

    post type_1 name
    post type_1 name

    post type_2 name
    post type_2 name

posts_table:

$table->enum('type', ['type_1', 'type_2', 'type_3'])->default('type_1');
$table->unsignedBigInteger('category_id')->index();
$table->foreign('category_id')->references('id')->on('categories');

categories_table:

$table->string('name');

类别型号:

return $this->hasMany('App\Models\Post');

后模型:

return $this->belongsTo('App\Models\Category');

我试过了:

$categories = ['category_1', 'category_2'];

foreach ($categories as $cat) {
    $postsType1[$cat->name] = $cat->posts()->where('type', 'type_1')->latest()->limit(2)->get();
    $postsType2[$cat->name] = $cat->posts()->where('type', 'type_2')->latest()->limit(2)->get();
}

但这是类别中的两个独立数组。我需要一个类别数组,每种类型有 2 个帖子。

【问题讨论】:

  • 您的帖子表是否有一个名为 category_id 的列,如果有,该列是否为每个条目设置为有效的 category_id?
  • 是的,确实如此。我忘了指定。

标签: php laravel eloquent


【解决方案1】:

您可以在多个条件下利用集合groupBy()

$posts = Post::query()
    ->latest()
    ->get()
    ->groupBy([
        function($post) {
            return $post->category->name;
        },
        function($post) {
            return $post->type;
        },
    ])
    ->map(function($records, $category) {
      return $records->sortKeys()->map(function($rows, $type){
          return $rows->take(2)->all();
      });
    })
    ->all();

如果您只想按类别名称分组并按帖子类型排序

$posts = Post::get()
    ->group(function($post){
        return $post->category->name;
    })
    -> map(function($value, $key){
        return $value->sortBy('type')->sortByDesc('created_at')->take(2);
    })
    ->all();

更新 为了避免无限制地获取所有 Post 记录,另一种选择是:

  • 在帖子表上创建复合索引以获得更好的查询性能
//in migration file for the posts table
$table->index(['type', 'category_id']);
  • 在 Category 模型上定义 3 个关系
class Category extends Model
{

    public function type1News()
    {
        return $this->hasMany(Post::class)->where('type', 'type_1')->latest();
    }

    public function type2News()
    {
        return $this->hasMany(Post::class)->where('type', 'type_2')->latest();
    }

    public function type3News()
    {
        return $this->hasMany(Post::class)->where('type', 'type_3')->latest();
    }
}

然后去获取数据

 $categories = Cache::remember('categoriesWithLatestNews', 3600, function() {
    $cats = Category::get();

    $cats->each->load([
        'type1News' => function($query){
            return $query->take(2);
        },
        'type2News' => function($query){
            return $query->take(2);
        },
        'type3News' => function($query){
            return $query->take(2);
        }
    ]);

    return $cats;
});

posts 表中有 100 万条记录,响应时间首次为 2.75 秒。 (没有复合索引响应时间超过120s)

然后在它被缓存指定的秒数之后,因此响应时间以毫秒为单位。

虽然这种方法需要多个数据库查询,但总共需要 31 个(10 个类别记录)查询:1 个查询所有类别,然后每个类别 3 个查询以获取关系。

【讨论】:

  • 我应该如何按类别限制/最新?
  • 不明白——你的意思是说要先按创建日期降序排序,然后再按类型升序排序?
  • 是的,我想为每种类型 ->latest()->limit(2)
  • @BraddyPhil 已将答案更新为首先按type 排序,然后按latest 排序,并根据您之前的评论限制记录-检查并让我知道这是否为您提供了所需的输出
  • 不,它不起作用。假设我有 1000 条新闻(不适合使用 all() 和 get()(无限制)方法迭代所有新闻)和 10 个类别。假设我每个类别需要 4 条新闻,例如,分为两种类型 - 重要(2 条新闻)和不那么重要(2 条新闻)。
猜你喜欢
  • 2019-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-30
  • 1970-01-01
  • 2014-08-30
  • 2017-01-19
  • 2011-06-24
相关资源
最近更新 更多