Mike_NotGuilty
Mike_NotGuilty

Reputation: 2405

Laravel - Map two relationships to one

I have a model events where I store informations about events. Every event belongs to one group. users of a event-group have the ability to reply if they attend at the event or not. This information is saved in a separate table event_replies.

Now with a simple relationship I can get all the replies of the event:

public function replies()
{
    return $this->hasMany('App\Models\EventReply','event_id','id');
}

or I can get all users of the group

public function users()
    {
        return $this->hasMany('App\Models\User','group_id','group_id');
    }

But loading the replies does not load all the users that didn't reply.

What I want is: The relation should return ALL users of the group. If they replied, the value should return, if not: the value should be null.

Is it possible to combine/map the Users-Relationship with the Replies-Relationship?

Edit

Here is an example how the JSON result should look like:

    [ 
   { 
      "id":1,
      "group":1,
      "name":"Event 1",
      "replies":[ 
         { 
            "name":"user 1",
            "reply":1 // replied
         },
         { 
            "name":"user 2",
            "reply":0 // replied
         },
         { 
            "name":"user 3",
            "reply":null // NO reply in event_replies
         },
         { 
            "name":"user 4",
            "reply":1 // replied
         }
      ]
   }
]

Edit 2

Events-Table:

id: int
name: String
group_id: int

Users-Table:

id: int
name: String
group_id: int

event_replies-Table:

event_id: int
user_id: int

Like I said before: My goal is to get a event with all users that belong to the group --> user.group_id = event.group_id. If they replied, the Reply should be in the user object. If not - the Reply object inside the user object should be null.

With a normal SQL query I would join all users and left join the replies.

Upvotes: 0

Views: 3082

Answers (2)

LobsterBaz
LobsterBaz

Reputation: 2003

If I understand properly, you want to "eager load" your Event model with nested users and their respective replies.

Get a single event:

$event = Event::find(1)->with('users.replies')->get();

Get all events:

$events = Event::all()->with('users.replies')->get();

Here's Laravel documentation about eager loading:

Upvotes: 1

Palak Jadav
Palak Jadav

Reputation: 1272

Get replies with user and define user relationship in EventReply model

public function replies()
{
   return $this->hasMany('App\Models\EventReply','event_id','id')->with('user');
}

EventReply.php

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

Upvotes: 2

Related Questions