Laravel Eloquent Eager根据列值加载

问题描述 投票:1回答:1

我得到了一个名为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;

我的尝试是:

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
        }
    }
}
laravel laravel-5 eloquent
1个回答
0
投票

您可以在Model类中进行设置,而不是这样做。

像这样。

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

检索:

qazxswpoi

试试吧。

© www.soinside.com 2019 - 2024. All rights reserved.