Home > OS >  Access to relation on another model
Access to relation on another model

Time:12-26

I have three tables, Owner, Garages, Orders Owner has "n" garages and each garage belongs to one owner, Each garage can have many orders, Now is it possible to only get orders from Owner model with relation instance? Owner model:

public function garages()
{
    return $this->hasMany(Garage::class);
}

Garage model:

public function owner()
{
    return $this->belongsTo(Owner::class);
}
public function orders()
{
    return $this->hasMany(Order::class);
}

CodePudding user response:

First of all, you should elaborate on how your models are defined. Guessing about how your database schemas are, you must fix your relationships:

Owner.php

public function garages()
{
    return $this->hasMany(Garage::class);
}

public function orders()
{
    return $this->hasManyThrough(Order::class, Garage::class);
}
Garage.php

public function owner()
{
    return $this->belongsTo(Owner::class);
}

public function orders()
{
    return $this->hasMany(Order::class);
}
Order.php 

public function garage()
{
    return $this->belongsTo(Garage::class);
}

Saying that, you can access your Owner's orders by doing

$owner = Owner::findOrFail($owner_id);
$orders = $owner->orders;
  • Related