mercredi 13 novembre 2019

Fetch data from many to many relationship with eloquent

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.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire