Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

v0sn's avatar
Level 1

Relationships between 3 tables

Hello,

i have the following tables

messages
- id
- user_id
- message

user
- id

likes
- id
- message_id
- user_id

User Model

public function messages()
{
return $this->hasMany(Message::class);
}

Message Model

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function likes()
    {
        return $this->hasMany(Like::class);
    }

Like Model

    public function user()
    {
        return $this->belongsTo(User::class);
    }

So an user can post messages, and these messages can be liked.. am i doing the relationships right? is there a better way?

thanks

0 likes
1 reply
realrandyallen's avatar

Looks pretty good to me - I’d also add the likes relationship on the User model as well.

Technically you could remove the id field from the likes table and do this:

$table->primary(['user_id', 'message_id']);

But in a way you kinda open a can of worms by doing that and it’s usually easier to just leave the id field like you have.

1 like

Please or to participate in this conversation.