Reputation: 42753
I have 2 models, store
and dvd
with many to many relationship
dvd
model:
public function stores() {
return $this->belongsToMany('App\store');
}
store
model:
public function dvds ( ) {
return $this->belongsToMany('App\dvd');
}
Then, in controller, when I need fetch data from both models, I use code like this:
$res_store = store::orderBy("id","desc")->get();
foreach( $res_store as $row ) {
$dvds = $row->dvds()->get();
foreach ($dvds as $dvd) {
// echo columns here
}
}
This works, but my question is, I'm doing this in correct way? I'm asking because it seems 2 loops for this simple relation is somehow inefficient.
Upvotes: 1
Views: 36
Reputation: 29258
No, this is not the right way.
When looping over a $store
, you can access the associated $dvd
records via $store->dvds
; there is no need to call $row->dvds()->get()
, as that is executing a new query with the same result of $store->dvds
. Full code should simply be:
$stores = Store::with("dvds")->orderBy("id", "DESC")->get();
foreach($stores AS $store){
foreach($store->dvds AS $dvd){
... // Do something with `$dvd`
}
}
The ::with("dvds")
clause is known as "Eager loading", and prevents $store->dvds
from needing execute another query behind the scenes.
Also, please name your models correctly. Classes in PHP are StudlyCase
, so Store
and DVD
, not store
and dvd
.
Upvotes: 2