【发布时间】: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? -
是的,确实如此。我忘了指定。