Edit: Updated to hasOne in both classes
I have two tables, Store
and Address
. One Store has one address and one address is associated with only one store.
In my Store
model, I have a hasOne
relationship.
public function store_address(): HasOne
{
return $this->hasOne(Address::class, 'id', 'address_id');
}
And in Address
model I have a hasOne
:
public function store(): HasOne
{
return $this->hasOne(Store::class, 'id', 'store_id');
}
Now I want to join these two tables using Eloquent with() with select *
from store
but want specific columns from the address
table.
Store::where('user_id', $user_id)
->select(\DB::raw('*')
->with(['store_address' => function($query) {
return $query->select(['distance_to_user as distance']);
}])
->orderBy('distance');
However it's not returning the correct distance
from the address table. How can I do that?
This is the error message I get:
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)