我正在尝试进行查询以获取所有访谈并在companiess表中获取公司名称。我只想返回公司表中的名称列。
我运行了一个查询日志,发现我的关系正在返回一个奇怪的查询。
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
而不是实际模型。
还有,有没有办法只返回上面的字段之一?
答案 0 :(得分:1)
找到了答案。您必须在原始查询中指定id
和company_id
才能起作用。
$interviews = Interview::select('id', 'title', 'company_id', 'slug', 'subtitle', 'posted_date')
->orderBy('created_at', 'DESC')
->with(['company:id,name'])
->get();