mardi 27 mars 2018

Eloquent - Eager loading the inverse

The main problem is that I need to eager load based upon dynamic tables. I need to find a way to produce an eloquent command that can yield me a collection in the following way..

  • Outside Diameter
    • Material
      • Manufacture Part Number
      • Manufacture Part Number
      • Manufacture Part Number
      • Manufacture Part Number
  • Outside Diameter
    • Material
      • Manufacture Part Number
      • Manufacture Part Number
      • Manufacture Part Number
      • Manufacture Part Number
    • ....

An eloquent command that I came up with that produces the non-desirable results are:

$tinker> App\Models\ManufacturePartNumber::with('outsideDiameters', 'materials', 'measurements')->get();

Which yields the following collection, given my relationships:

  • Manufacture Part Number
    • Outside Diameter
      • Material
  • Manufacture Part Number
    • Outside Diameter
      • Material
  • Manufacture Part Number
    • Outside Diameter
      • Material
    • ....

While playing around in tinker, I attempted to run this command which made since to me. It produces an error, which I half expected.

$tinker> App\Models\OutsideDiameter::with('materials', 'manufacturePartNumbers')->get(); Illuminate\Database\Eloquent\RelationNotFoundException with message 'Call to undefined relationship [materials] on model [App\Models\OutsideDiameter].'

Ultimately, my problem is that I need to build an eloquent command that can eager load the results in the desired way. The command will be dynamic, from the stance, that the model relationships are based upon a user's interaction with the site. Think something like Amazon with checkbox filters on the left side. The way that I see that is that I'd need to come up with every possible combination of models and create the corresponding pivot tables with all that data. That doesn't seem efficient to me...

Any ideas on how I can get to my goal?

My given models are defined as the following:

class ManufacturePartNumber extends Eloquent  
{  
  public function materials()  
  {  
    return $this->belongsToMany(\App\Models\Material::class);  
  }   

  public function outsideDiameters()  
  {  
    return $this->belongsToMany(\App\Models\OutsideDiameter::class);  
  }  
}

class Material extends Eloquent  
{  
  public function manufacturePartNumbers()  
  {  
    return $this->belongsToMany(\App\Models\ManufacturePartNumber::class);  
  }   
}

class OutsideDiameter extends Eloquent  
{  
  public function manufacturePartNumbers()  
  {  
    return $this->belongsToMany(\App\Models\ManufacturePartNumber::class);  
  }  
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire