0
votes

Users can attach files to the post: images or videos.

The structure of the database is as follows:

posts
   id
images
   id
videos
   id
post_attachment
   post_id
   attachment_id (id from images or videos table)
   attachment_type ('image' or 'video')

The difficulty is that, depending on the type of attachment, we should refer to different tables.

What relation of laravel functions should I apply to the Post model to get all the attachments through the post_attachment table?

I think this relationship is from a series of morph, but I can not understand exactly which one.

class Post {
     public function attachments () {
        return $this->morph?????
     }
}

Help me please to write correct relation for this case.

1

1 Answers

1
votes

You might not need a pivot table at all, you can just create relationships between Attachmentand Video using hasMany(), for example. Alternatively, to simplify your database structure, I would organize everything under a PostAttachment model

An example would be:

class Post extends Model
{
    public function attachment(){
        return $this->hasMany(Attachment::class);
    }
}

and your Attachment model:

class Attachment extends Model
{
    public function post(){
        return $this->belongsTo(Post::class);
    }
}

and perhaps on your table, have a field which specifies the different types of attachments allowed:

$table->enum('attachment_type', ['video', 'image']);