【问题标题】:Laravel Eloquent whereHas error unknown columnLaravel Eloquent whereHas error unknown column
【发布时间】:2017-06-09 00:41:24
【问题描述】:

我正在尝试获得产品的最低价格

$items=Item::whereHas('products', function($query){
        $query->orderBy('price','asc')->first();
    })->with('page')->get();

模型Item.php

public function products(){
    return $this->hasMany('App\Product','item_id','id');
}

错误

找不到列:1054 'where 子句'中的未知列 'items.id'(SQL:select * from products where products.item_id = items.id order by price asc 限制 1)

【问题讨论】:

  • 请运行您在 phpmyadmin 中出错的查询并检查它是否给出错误?如果是这样,请检查您的 laravel 查询
  • 我认为查询给出了错误,因为它缺少“来自产品,项目”
  • 是的,你也错过了
  • 知道如何解决吗?
  • 可以使用 DB::select(DB::raw('your-query')) 执行并获取一个集合

标签: php laravel eloquent


【解决方案1】:

尝试以下方法:

DB::select(DB::raw("select * from products where products.item_id = items.id order by price asc limit 1"));

【讨论】:

    【解决方案2】:

    我查阅了 Laravel Eloquent 文档并稍微更改了代码,现在它可以工作了。

        $items=Item::with(['products' => function($query){
            $query->orderBy('price','asc')->first();
        },'page'])->get();
    

    https://laravel.com/docs/5.3/eloquent-relationships

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 1970-01-01
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      • 2019-12-28
      • 2020-09-16
      • 1970-01-01
      • 2014-09-30
      相关资源
      最近更新 更多