2017-08-16 85 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();