2017-08-16 82 views
1

我有以下查询,我要筛选多态性关系:Laravel 5.2 - 查询生成器语法筛选多态关系?

$companyLogo = $user->company->files->where('file_type', 'Logo')->first(); 

当我启用查询日志,这是我得到什么:

"query" => "select * from `files` where `files`.`fileable_id` = ? and `files`.`fileable_id` is not null and `files`.`fileable_type` = ?" 
"bindings" => array:2 [▼ 
    0 => 1 
    1 => "App\Company" 
] 

正如你可以在不包括我where子句?

*更新*

这是polymorhpic关系我公司和文件模型之间:

class File extends Model { 

    protected $fillable = [ 
    'name', 
    'path', 
    'size', 
    'mime_type', 
    'file_type', 
    'fileable_id', 
    'fileable_type', 

    ]; 

    public function fileable() 
    { 
     return $this->morphTo(); 
    } 

} 


class Company extends Model { 

    public function files() 
    { 
     return $this->morphMany('App\File', 'fileable'); 
    } 

} 

我不知道为什么查询出师表包括where子句无论是。语法是否正确过滤多态关系?一家公司可以有不同类型的文件,例如文件,标志等,但我想选择标志。

+2

'file_type'或'fileable_type'? – aynber

+1

另外你输出的绑定都没有'Logo'的查询?你确定他们是正确的问题吗? – Purgatory

+0

您的日志中的查询似乎不符合您的问题中的查询 – chiliNUT

回答

0

我决定重构如下:

添加了一个查询范围,以文件类:

public function scopeCompanyLogo($query, $id) 
{ 
    $query->where('file_type','=', 'Logo') 
     ->where('fileable_type','=', 'App\Company') 
     ->where('fileable_id','=', $id); 
} 

现在得到的公司的标志如下:

$companyLogo = File::CompanyLogo($user->company_id)->first(); 

*更新*

刚刚发现了什么是wron摹与原来的代码太

而不是做这个的:

$companyLogo = $user->company->files->where('file_type', 'Logo')->first(); 

它应该是:

$companyLogo = $user->company->files()->where('file_type', 'Logo')->first();