Search code examples
laraveleloquentsubquerylaravel-6eloquent-relationship

Laravel Multiple Table Subquery


I'm using Laravel 6.0 I have 4 different tables.

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

I'd like to list posts in two date ranges from the post_category table. For example

PostCategory::whereBetween('created_at',[$from, $to])->get();

The result should be:

Result

https://i.ibb.co/y53PmJ9/image.png

How can I do that?

Models: PostCategory

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');
}}

TextPost

class TextPost extends Model
{
use SoftDeletes;
protected $table = 'text_post';
public $timestamps = true;

protected $fillable = [
    'title',
    'content',
];
}

PhotoPost

class PhotoPost extends Model
{
use SoftDeletes;
protected $table = 'photo_post';
public $timestamps = true;

protected $fillable = [
    'title',
    'image',

];
}

Video Post

class VideoPost extends Model
{
use SoftDeletes;
protected $table = 'video_post';
public $timestamps = true;

protected $fillable = [
    'title',
    'video_source_url',

];
}

Solution

  • Sure, it's possible. But since we just know your database design but not your codebase, it's hard to say. Intuitively I'd go with a polymorphic relationship.