Php Laravel 5.2-过滤多态关系的查询生成器语法?
我在下面的查询中要筛选多态关系:Php Laravel 5.2-过滤多态关系的查询生成器语法?,php,laravel-5.2,laravel-query-builder,Php,Laravel 5.2,Laravel Query Builder,我在下面的查询中要筛选多态关系: $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
$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条款
*更新*
这是我在公司和文件模型之间的多元关系:
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子句。过滤多态关系的语法正确吗?公司可以有不同类型的文件,例如文档、徽标等,但我想选择徽标。我决定按如下方式重构:
$companyLogo = File::CompanyLogo($user->company_id)->first();
向文件类添加了查询范围:
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();
*更新*
只是想知道原始代码有什么问题
而不是这样做:
$companyLogo = $user->company->files->where('file_type', 'Logo')->first();
应该是:
$companyLogo = $user->company->files()->where('file_type', 'Logo')->first();
文件类型
或可文件类型
?您输出的查询也没有徽标
?您确定它们是正确的查询吗?您日志中的查询似乎与您日志中的查询不一致question@chiliNUT我过滤多态关系的语法正确吗?查询日志与查询相关。查看我的更新。@aynber我想按文件类型筛选-查看我的更新。