Eann
Eann

Reputation: 93

Relationship not working in laravel eloquent

i having two relationship model in my project. CarPool & Ride & User.

In my CarPool model

public $with=['user','ride'];

public function user(){
    return $this->belongsTo('App\User');
}

public function ride(){
    return $this->hasMany('App\Ride');
}

In my ride model

public $with=['user','carpool'];

public function user(){
    return $this->belongsTo('App\User');
}

public function carpool(){
    return $this->belongsTo('App\CarPool');
}

In my expected scenario, when user enter to "My Ride" page, it will display all ride took by user.(For example users took 3 rides).So the list having 3 column. Each ride column having carpool information and driver information.

In my controller, i use this to get the ride belongs to user.

$user_id=Auth::user()->id;

    $rides= Ride::where('user_id',$user_id)->get();

But after i check the result. Seem like the carpool relationship has not connected because there was null. Is my relationship not correct?

enter image description here

My table in database car_pools Table enter image description here

rides Table enter image description here

Upvotes: 1

Views: 1617

Answers (3)

Jathin Prasad
Jathin Prasad

Reputation: 119

Try after giving foreign-key and primary key both in the relation mapping function. Because sometimes if you are just giving foreign key, Then the model will try to connect to the other model with its primary key. If you are not using the primary key for relation specify the other key in the relation function.

Upvotes: 0

Eann
Eann

Reputation: 93

Problems solved, although is not eagle loading but still can work in another ways. I changed my ride model by removing the carpool. So now is

public $with=['user'];

Then i call the data by {{ $ride->carpool->title }} Not same with my expectation but at least working.

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163958

It really looks like you don't have car_pool_id fields in the rides table that has related CarPool ID in it.

If you have this fields, but the name is different, add the foreign key name to the relationship:

public function carpool()
{
    return $this->belongsTo('App\CarPool', 'custom_column_name');
}

Upvotes: 0

Related Questions