Koushik Das
Koushik Das

Reputation: 10813

Eloquent model relationship for final table

I've the following tables

Cities (City model)


+----+-------+
| id | name  |
+----+-------+
|  1 | tokyo |
+----+-------+


events (Event model)

+----+--------------------+---------+
| id |       title        | city_id |
+----+--------------------+---------+
|  1 | Biggest event ever |       1 |
+----+--------------------+---------+


event_user_applications (EventUserApplication model)


+----+----------+---------+
| id | event_id | user_id |
+----+----------+---------+
|  1 |        1 |       1 |
+----+----------+---------+

How do I get the city on EventUserApplication model. I tried both of this in the EventUserApplication

    public function city()
    {
//        return $this->belongsTo('App\Model\City', 'city_id')->using('App\Model\Event', 'event_id');
//        return $this->hasOneThrough('App\Model\City', 'App\Model\Event', 'city_id', 'id');
    }

Can't get any of this to work. Already spent hours. Please help. Thank you in advance.

Upvotes: 0

Views: 97

Answers (2)

Parvej Ahammad
Parvej Ahammad

Reputation: 45

In that case you can use hasOnThrough relationship EventUserApplication has One city Through Event.

Edit:The 5th parameter should be event_id and there should be another parameter which is id (foreign key of event table)

Upvotes: 0

Koushik Das
Koushik Das

Reputation: 10813

I solved it with the help of my friend. This is what I did to get the city.

$applications = EventUserApplication::with(
        'user:id,name,phone,email,date_of_birth',
        'event:id,title,area_id,area_city_id',
        'event.city' // nester eager loading
    )->latest()->get();

In the Event model, I already had this

public function city()
{
    return $this->belongsTo('App\Model\City', 'area_city_id');
}

It's the Nester Eager Loading which was needed.

Upvotes: 1

Related Questions