Has One Through Relationship in laravel?

The "has-one-through" relationship links models through a single relation.

Example : in a vehicle repair shop application, each Mechanic may have one Car, and each Car may have one Owner. While the Mechanic and the Owner have no direct connection, the Mechanic can access the Owner through the Car itself.

mechanics
id - integer
name - string

cars
id - integer
model - string
mechanic_id - integer

owners
id - integer
name - string
car_id - integer

File name : index.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Mechanic extends Model
{

public function carOwner()
{
return $this->hasOneThrough('App\Owner', 'App\Car');
}
}

The first argument passed to the hasOneThrough method is the name of the final model we wish to access, while the second argument is the name of the intermediate model.


If you would like to customize the keys of the relationship, you may pass them as the third and fourth arguments to the hasOneThrough method. The third argument is the name of the foreign key on the intermediate model. The fourth argument is the name of the foreign key on the final model. The fifth argument is the local key, while the sixth argument is the local key of the intermediate model

File name : index.php

class Mechanic extends Model
{
/**
* Get the car's owner.
*/
public function carOwner()
{
return $this->hasOneThrough(
'App\Owner',
'App\Car',
'mechanic_id', // Foreign key on cars table...
'car_id', // Foreign key on owners table...
'id', // Local key on mechanics table...
'id' // Local key on cars table...
);
}
}





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here


Ittutorial