【发布时间】:2020-06-02 22:56:39
【问题描述】:
编辑:在两个类中更新为 hasOne
我有两张桌子,Store 和 Address。一个店铺有一个地址,一个地址只关联一个店铺。
在我的Store 模型中,我有一个hasOne 关系。
public function store_address(): HasOne
{
return $this->hasOne(Address::class, 'id', 'address_id');
}
在Address 模型中,我有一个hasOne:
public function store(): HasOne
{
return $this->hasOne(Store::class, 'id', 'store_id');
}
现在我想使用 Eloquent with() 和来自 store 的 select * 连接这两个表,但想要来自 address 表的特定列。
Store::where('user_id', $user_id)
->select(\DB::raw('*')
->with(['store_address' => function($query) {
return $query->select(['distance_to_user as distance']);
}])
->orderBy('distance');
但是它没有从地址表中返回正确的distance。我该怎么做?
这是我收到的错误消息:
Column not found: 1054 Unknown column 'distance' in 'order clause' (SQL: select *, from `store` where `store`.`user_id` = 12 and `store`.`deleted_at` is null order by `distance` asc)
【问题讨论】: