在 Laravel Eloquent 中获取 HasOne 关系中的特定列

danni114

编辑:在两个类中都更新为 hasOne

我有两张桌子,StoreAddress一个商店有一个地址,一个地址只与一个商店相关联。

在我的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() 和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');

但是它没有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)
阿里·沙里芬耶斯坦

我假设你的表的结构

地址:

id | store_id| body | distance_to_user
----------------------------------------
 1 | 1       |China | 100

对于商店:

id | name
--------------
 1 | Store_01

你应该有像这样的模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Address extends Model
{
    //

    public function store()
    {
        return $this->belongsTo('App\Store');
    }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Store extends Model
{
    //
    public function address()
    {
        return $this->hasOne('App\Address');
    }
}

现在在您的控制器中:

        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();
        }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章