2017-12-19 17 views
1

bekam ich ein Modell namens Tag und enthält eine Spalte tag_type die Werte einer von drei sein können: company, office oder school.Laravel Eloquent Eager Loading je nach Spaltenwert

Für jeden gibt es ein entsprechendes Modell Company, Office und School und in jeder von uns eine inverse Beziehung return $this->belongsTo('App\Tag') zum Tag Modell, das im Austausch hat, eine hasOne Bezug auf jede dieser drei Modelle return $this->hasOne('App\Company')

Wie kann ich einen bestimmten Tag mit eifrigen Laden auf diese drei Modelle holen, die das Tag und speziell eines dieser Modelle holen wird in Abhängigkeit von der bei dieser tag_type

Mein Versuch war:

$tags = Tag::where('ref_id', 123)->get(); 
    foreach ($tags as $tag) { 
     $collectionTag = null; 
     if($tag->tag_type == 'Company'){ 
      $collectionTag = $tag->company()->first(); 
     } 
     if($tag->tag_type == 'Office'){ 
      $collectionTag = $tag->office()->first(); 
     } 
     if($tag->tag_type == 'School'){ 
      $collectionTag = $tag->school()->first(); 
     } 
     $tag['collectionTag'] = $collectionTag; 
    } 
    return $tags; 
+1

Ich schlage vor, dass Sie in diesen Link schauen. [Polymorphe Beziehungen von Laravel] (https://laravel.com/docs/5.5/eloquent-relationships#polymorphic-relations). Im Moment nicht sicher, wie Ihr Szenario abgebildet wird, aber es bietet eine typbasierte Verknüpfung zu Modellen –

Antwort

0

Anstatt dies zu tun, können Sie in der Model-Klasse festlegen.

So.

class Tag extends Model { 
    public function tagType() { 
     if($this->tag_type === "Company"){ 
      return $this->hasOne(Company::class, 'company_id', 'id'); //you can change column based on your database structure 
     } else if($this->tag_type === "Office"){ 
      return $this->hasOne(Office::class, 'office_id', 'id'); //you can change column based on your database structure 
     } else { 
      return $this->hasOne(School::class, 'school_id', 'id'); //you can change column based on your database structure 
     } 
    } 
} 

Abrufen:

Tag::where('CONDITION')->with('tagType')->get(); 

dies ausprobieren.

Verwandte Themen