Laravel 多个 Table 子查询
Laravel Multiple Table Subquery
我正在使用 Laravel 6.0
我有 4 个不同的 tables.
表格:
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 table 两个日期范围内的帖子。例如
PostCategory::whereBetween('created_at',[$from, $to])->get();
结果应该是:
结果
我该怎么做?
型号:
Post类别
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');
}}
文字Post
class TextPost extends Model
{
use SoftDeletes;
protected $table = 'text_post';
public $timestamps = true;
protected $fillable = [
'title',
'content',
];
}
照片Post
class PhotoPost extends Model
{
use SoftDeletes;
protected $table = 'photo_post';
public $timestamps = true;
protected $fillable = [
'title',
'image',
];
}
视频Post
class VideoPost extends Model
{
use SoftDeletes;
protected $table = 'video_post';
public $timestamps = true;
protected $fillable = [
'title',
'video_source_url',
];
}
当然,这是可能的。但是因为我们只知道你的数据库设计而不是你的代码库,所以很难说。直觉上我会选择 polymorphic relationship.
我正在使用 Laravel 6.0 我有 4 个不同的 tables.
表格:
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 table 两个日期范围内的帖子。例如
PostCategory::whereBetween('created_at',[$from, $to])->get();
结果应该是:
结果
我该怎么做?
型号: Post类别
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');
}}
文字Post
class TextPost extends Model
{
use SoftDeletes;
protected $table = 'text_post';
public $timestamps = true;
protected $fillable = [
'title',
'content',
];
}
照片Post
class PhotoPost extends Model
{
use SoftDeletes;
protected $table = 'photo_post';
public $timestamps = true;
protected $fillable = [
'title',
'image',
];
}
视频Post
class VideoPost extends Model
{
use SoftDeletes;
protected $table = 'video_post';
public $timestamps = true;
protected $fillable = [
'title',
'video_source_url',
];
}
当然,这是可能的。但是因为我们只知道你的数据库设计而不是你的代码库,所以很难说。直觉上我会选择 polymorphic relationship.