[英]Get Specific Columns in HasOne relationship in Laravel Eloquent
Edit: Updated to hasOne in both classes编辑:在两个类中都更新为 hasOne
I have two tables, Store
and Address
.我有两个表, Store
和Address
。 One Store has one address and one address is associated with only one store.一个商店有一个地址,一个地址只与一个商店相关联。
In my Store
model, I have a hasOne
relationship.在我的Store
模型中,我有一个hasOne
关系。
public function store_address(): HasOne
{
return $this->hasOne(Address::class, 'id', 'address_id');
}
And in Address
model I have a hasOne
:在Address
模型中,我有一个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.现在我想使用 Eloquent with() 和select *
from store
连接这两个表,但想要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');
However it's not returning the correct distance
from the address table.但是它没有从地址表返回正确的distance
。 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)
I assume the structure of your tables我假设你的表的结构
Addresses:地址:
id | store_id| body | distance_to_user
----------------------------------------
1 | 1 |China | 100
and for Stores:对于商店:
id | name
--------------
1 | Store_01
You should have Models like:你应该有像这样的模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Address extends Model
{
//
public function store()
{
return $this->belongsTo('App\Store');
}
}
and和
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Store extends Model
{
//
public function address()
{
return $this->hasOne('App\Address');
}
}
now in your controller:现在在您的控制器中:
public function index()
{
//return Store::with(['address' => function($q){
// $q->select('distance_to_user as distance','store_id');
// }])->get();
return Store::leftJoin('addresses', 'addresses.store_id', '=', 'stores.id')
->select('stores.id','stores.name','distance_to_user as distance')
// OR use ->select('stores.*','addresses.id as address_id','distance_to_user as distance')
->orderBy('distance','Desc')
->get();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.