0
votes

I'm learning eloquent relationship on Laravel and i got question on the hasonethrough by using the same table design as Laravel's docs

tables
mechanics (id, name)
cars (id, model, mechanic_id)               
owners (id, name, car_id)

then I define the relationship at the mechanic model to access car owner

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

this will return

array:4 [▼
  "id" => 1
  "name" => "Ricky"
  "car_id" => 1
  "laravel_through_key" => 1
]

my question is can I get the car model using my hasOnethrough relation ?

1

1 Answers

0
votes

yes you can ....

in your Owner model setup the car relation

class Owner extends Model
{
    public function car() {
        return $this->belongsTo('App\Car','car_id');
    }   
}   

then you could use those relations like this:

$value=Mechanic::find($mechanic_id)->with('carOwner.car')->get();

the $value will hold the car owner with his car