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

shujau's avatar

Need a solution for a relationship in Models

Ok.. a have three tables . . two main tables and one pivot table,, users, notification_user, notifications..

users can have many notifications and each notification belongs to many users this relation is simple to understand and do in models.

Problem is the next one...

user who sends the notification... his id should also appear in the notification table..

a user can send many messages, each message is sent by one user.... how do u show this relation in model user and notification model. do i just add another one to many relation to the same 2 tables?

sorry if this is confusing.. im very new here. someone help....

0 likes
3 replies
EliasSoares's avatar
Level 10

@shujau

Yes, define two relationships. Your notification have only one "sender_user" right?

So this is the relationship "schema":

1st: relationship Many to Many

  • User belongsToMany Notification (A user has many received notifications) [received_notifications]
  • Notification belongsToMany User (A notification has many recipient) [recipients]

I suggest naming the pivot table as notification_recipient_users and manually set the pivot table name on relationship, instead of the conventional naming, since your relation isn't so simple.

2nd: relationship One to Many

  • Notification belongsTo User (A notification has a sender) [sender]
  • User hasMany Notification (A user has many sent notifications) [sent_notifications]

I suggest naming your foreign key on notification as sender_user_id.

Since you have two relations with different meanings, you should call they on a suggestive name, as I suggested on square brackets.

1 like
shujau's avatar

@EliasSoares Thanks :D

1st: relationship Many to Many

"User belongsToMany Notification (A user has many received notifications) [received_notifications]" shouldnt this be

User hasMany Notification (A user has many received notifications) [received_notifications]

EliasSoares's avatar

manyToMany relationships uses belongsToMany definition on both ways.

:)

1 like

Please or to participate in this conversation.