I have 3 tables
Products: Id, name
Batches: Id, number, product_id
Sales: Id, batch_id, Quantity, price
Product Model:
public function batches()
{
return $this->hasMany('App\Batch');
}
Batch Model:
public function product()
{
return $this->belongsTo('App\Product');
}
public function sales()
{
return $this->hasMany('App\Sale');
}
Sale Model:
public function batch(){
return $this->belongsTo('App\Batch');
}
Controller code:
$batches = App\Batch::with(['sales','product'])->where('id',5)->get();
This code works perfectly with a single loop to fetch product:
foreach($batches as $batch)
{
echo $batch->product->name
}
Until i used two loops before i can access sales, why ?
Is there a way i can fetch sales at the first loop ?
foreach($batches as $batch)
{
foreach($batch->sales as $sale)
echo $sale->price.'<br>';
}