我遇到以下问题,我在Laravel中使用scope
,我有以下关系:
询问
pickup_address
dropoff_address
Notes
这在模型中引用:
public function pickup_address() {
return $this->belongsTo('App\Address', 'pickup_address', 'id');
}
我想返回查询,以及存储在postcode
表中的Address
。我只想从这张表中找到这一栏,并完成了以下内容:
return $query->with(['pickup_address' => function ($query) {
$query->select('postcode');
}])->get();
这给出了以下(json):
{
"id":1,
"pickup_address":null
"notes":"hello world",
"created_at":"2017-06-08 09:56:52",
"updated_at":"2017-06-08 09:56:52"
}
这不是给出邮政编码而只是将pickup_address
作为空。但是,删除$query->select('postcode')
会给出:
{
"id":1,
"pickup_address": {
"id":140,
"house_number":null,
"address_1":"Address 1",
"address_2":null,
"postcode":"POSTCODE",
"city":"CITY",
"county":"C0UNTY",
"created_at":"2017-06-08 09:56:23",
"updated_at":"2017-06 0}",
"notes":"Hello world","
"created_at":"2017-06-08 09:56:52",
"updated_at":"2017-06-08 09:56:52"
}
但是,我正在使用Vue
并使用表,所以我只需要返回与列匹配的特定字段,而不是返回整个对象。
有人可以提出解决方案吗?我在网上关注了一些示例,他们建议$query->select('postcode')