我得到了一个名为Tag
的模型,它包含一个tag_type
列,其值可以是三个中的一个:company
,office
或school
。
每个都有一个相应的模型Company
,Office
和School
,并且在每一个中我们与return $this->belongsTo('App\Tag')
模型有一个反比关系Tag
,作为交换,hasOne
与这三个模型中的每一个都有return $this->hasOne('App\Company')
关系tag_type
如何获取特定标签,并急切加载这三个模型,这三个模型将获取标签,特别是这些模型中的一个取决于 $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;
我的尝试是:
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
}
}
}
您可以在Model类中进行设置,而不是这样做。
像这样。
Tag::where('CONDITION')->with('tagType')->get();
检索:
qazxswpoi
试试吧。