I am new to Laravel. I'm having a lot of trouble getting a very-nested relationship to work correctly in laravel.
The wanted behaviour is as follows,
I have 5 Models. Purchase
, Inventory
, Slab
, Scarting
and FloorTile
.
I have one to one relation between Purchase and Inventory Models, while inventory have further relation with slab, scarting and floortile.
I have purchase id and want to get data from inventory
table, then get a slab_id
, scarting_id
or floorTile_id
from inventory
table and get data from the respective table.
The slab_id
, scarting_id
and floorTile_id
can be multiple against inventory id
.
I don't know how to get data every iteration.
Purchase Model:
<?php
namespace App;
use App\Inventory;
use Illuminate\Database\Eloquent\Model;
class Purchase extends Model
{
public function inventory()
{
return $this->hasOne('App\Inventory');
}
}
Inventory Model:
<?php
namespace App;
use App\Slab;
use App\Scarting;
use App\FloorTile;
use App\Purchase;
Use App\StandardSize;
use Illuminate\Database\Eloquent\Model;
class Inventory extends Model
{
public function purchase()
{
return $this->belongsTo('App\Purchase');
}
public function standatdSize()
{
return $this->hasOne('App\StandardSize');
}
public function slab()
{
return $this->hasOne('App\Slab');
}
public function scarting()
{
return $this->hasOne('App\Scarting');
}
public function floorTile()
{
return $this->hasOne('App\FloorTile');
}
}
I have tried this:
$purchase = Purchase::where('factoryName', $factoryName)->with('inventory.slab')->get();
The result is as follows:
{
"id": 36,
"fname": "Sama",
"lname": "Jojo",
"factoryName": "Sama Inc.",
"cnic": "3216542",
"area": "Johar town",
"city": "Lahore",
"province": "Punjab",
"phone1": "45678912345",
"phone2": "45678912345",
"inventory_ID": 10,
"created_at": "2019-03-19 12:11:45",
"updated_at": "2019-03-19 12:11:45",
"inventory": {
"id": 10,
"purchase_id": 36,
"marbleType": "1",
"totalSquareFt": 25,
"priceperSquareFt": 230,
"totalPurchasePrice": 25000,
"standardSize_ID": "5",
"salePrice": 250,
"miliMeter": "6mm",
"slab_ID": 1,
"scarting_ID": null,
"floorTile_ID": null,
"created_at": "2019-03-19 12:11:45",
"updated_at": "2019-03-19 12:11:45",
"slab": null
}
}
Even there is data available against slab but still its showing NULL.