我有一个名为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;
答案 0 :(得分:0)
您可以在Model类中设置。而不是这样做。
喜欢这个。
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
}
}
}
检索:
Tag::where('CONDITION')->with('tagType')->get();
试试这个。