Laravel Eloquent Eager根据列值加载

时间:2017-12-19 04:15:37

标签: laravel laravel-5 eloquent

我有一个名为Tag的模型,其中包含一列tag_type,其值可以是三个中的一个:companyofficeschool

对于每个模型都有相应的模型CompanyOfficeSchool,并且每个模型都与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;

1 个答案:

答案 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();

试试这个。