【问题标题】:Get Specific Columns in HasOne relationship in Laravel Eloquent在 Laravel Eloquent 中获取 HasOne 关系中的特定列
【发布时间】:2020-06-02 22:56:39
【问题描述】:

编辑:在两个类中更新为 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() 和来自 storeselect * 连接这两个表,但想要来自 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)

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    我假设你的表格结构

    地址:

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

    【讨论】:

    • 嗨,阿里,感谢您的回答。我将其更改为hasOne,但似乎distance 列在我的查询中不可用。我用错误消息更新了描述。
    • 我不知道这个问题中的 $query 是什么。或者你的表结构和列是什么。所以我不得不猜测。试试 ->orderBy('distance_to_user ');或返回 $query->select(['distance_to_user as distance']) ->orderBy('distance');
    • 它仍然显示列distance_to_user 未找到。我要更新$query 说清楚
    • 所以我需要知道您的表格的列和您的完整代码。但是,如果您更准确地阅读我的答案,您将知道您可以做什么
    • 非常感谢阿里!
    猜你喜欢
    • 2016-03-17
    • 1970-01-01
    • 2021-12-30
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 2019-11-19
    • 1970-01-01
    相关资源
    最近更新 更多