简体   繁体   English

Laravel 5.2-查询生成器语法来过滤多态关系?

[英]Laravel 5.2 - Query Builder Syntax To Filter Polymorphic Relationship?

I have the following query where I want to filter a polymorphic relationship: 我有以下查询要过滤多态关系:

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

When I enable the query log this is what I get: 当我启用查询日志时,这就是我得到的:

"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"
]

As you can it is not including my where clause? 您可以不包括我的where子句吗?

* Update * *更新*

This is the polymorhpic relationship I have between company and file models: 这是公司和文件模型之间的多态关系:

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');
   }

 }

I'm not sure why the query inst including the where clause either. 我不确定为什么查询inst包含where子句。 Is the syntax correct to filter a polymorphic relationship? 语法是否正确以过滤多态关系? A company can have different types of files eg documents, logo etc but I want to select the logo. 公司可以使用不同类型的文件,例如文档,徽标等,但是我想选择徽标。

I decided to refactor as follows: 我决定重构如下:

Added a query scope to the File class: 向File类添加了查询范围:

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

Now get the company logo as follows: 现在获得公司徽标,如下所示:

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

* Update * *更新*

Just figured what was wrong with original code too 刚刚也知道原始代码有什么问题

Instead of doing this: 而不是这样做:

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

It should have been: 应该是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM