【发布时间】:2021-06-26 13:46:54
【问题描述】:
我正在使用 Laravel 6.0 我有 4 张不同的桌子。
表格:
post_category
| id | relation_post_id | post_type | category_id |
|---|
photo_post
| id | title | image | created_at |
|---|
text_post
| id | title | content | created_at |
|---|
video_post
| id | title | video_source_url | created_at |
|---|
我想列出 post_category 表中两个日期范围内的帖子。例如
PostCategory::whereBetween('created_at',[$from, $to])->get();
结果应该是:
结果
我该怎么做?
型号: 邮政分类
class PostCategory extends Model
{
use SoftDeletes;
protected $table = 'post_category';
public $timestamps = true;
protected $fillable = [
'relation_post_id',
'post_type', // 1: text, 2: photo, 3: video
'category_id',
];
public function text()
{
return $this->belongsTo('App\TextPost','relation_post_id','id');
}
public function photo()
{
return $this->belongsTo('App\PhotoPost','relation_post_id','id');
}
public function video()
{
return $this->belongsTo('App\VideoPost','relation_post_id','id');
}}
文字发布
class TextPost extends Model
{
use SoftDeletes;
protected $table = 'text_post';
public $timestamps = true;
protected $fillable = [
'title',
'content',
];
}
照片发布
class PhotoPost extends Model
{
use SoftDeletes;
protected $table = 'photo_post';
public $timestamps = true;
protected $fillable = [
'title',
'image',
];
}
视频发布
class VideoPost extends Model
{
use SoftDeletes;
protected $table = 'video_post';
public $timestamps = true;
protected $fillable = [
'title',
'video_source_url',
];
}
【问题讨论】:
-
能否提供您目前拥有的 Eloquent 模型的代码?
-
好的,我更新了问题,谢谢
-
啊,好吧。很基本。您拥有它的方式会使拥有所有这些模型的数组变得很麻烦。您必须分别过滤它们,然后合并它们。考虑使用下面提到的多态关系,因为您的示例似乎几乎注定了这种情况,并且会使您的编程生活更轻松。
标签: laravel eloquent subquery laravel-6 eloquent-relationship