【发布时间】:2019-11-22 20:33:44
【问题描述】:
我正在尝试进行查询以获取所有采访并在公司表中获取公司名称。我只想返回公司表中的名称列。
我运行了一个查询日志,发现我的关系返回了一个奇怪的查询。
Laravel 版本 6.5.2
我原本拥有的东西
$interviews = Interview::select('title', 'slug', 'subtitle', 'posted_date')
->orderBy('created_at', 'DESC')
->with(['company' => function($query) {
$query->select('id','name');
}])
->get();
我现在使用的只是为了测试关系是否有效:
\DB::enableQueryLog();
$interviews = Interview::select('title', 'slug', 'subtitle', 'posted_date')
->orderBy('created_at', 'DESC')
->with('company')
->get();
dd(\DB::getQueryLog());
公司模式:
public function interview() {
return $this->hasOne('App\Interview', 'company_id', 'id');
}
面试模型:
public function company() {
return $this->belongsTo('App\Company', 'id', 'company_id');
}
结果:
select `title`, `slug`, `subtitle`, `posted_date` from `interviews` where `interviews`.`deleted_at` is null order by `created_at` desc
select * from `companies` where 0 = 1 and `companies`.`deleted_at` is null
我试图弄清楚为什么它返回 where 0 = 1 而不是实际模型。
另外,有没有办法只返回上面我这样的一个字段?
【问题讨论】:
标签: php laravel laravel-5 eloquent