Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Mohemos's avatar

Relationship with multiple instances

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>';

}

0 likes
4 replies
Mohemos's avatar

@bnazarov@abv.bg Thanks for the clarification, I've gotten what i wanted; Am sorry for the bad text formatting, am new to this platform and i don't know how to format codes here.

Please or to participate in this conversation.