【问题标题】:Laravel "where" query the relationship tableLaravel "where" 查询关系表
【发布时间】:2016-05-20 20:22:58
【问题描述】:

这是我的查询:

$items = UserItems::with('item')
            ->where('user_id','=',$this->id)
            ->where('quantity','>',0)
            ->where('items.type','=',"shirt")
            ->get();

我需要typeshirt 的所有项目。

查询返回:

Column not found: 1054 Unknown column 'items.type' in 'where clause'

由于某些原因,items 在此查询中未被识别为表,我无法在其上使用 `where。

那么我如何获取项目类型为shirt的所有用户项目?

【问题讨论】:

  • 您的表是“item”还是“items”?如果是,则将 -> with('item') 更改为 with('items'),否则,将 -> ->where('items.type','=',"shirt") 更改为 ->where(' item.type','=',"shirt")
  • 我都试过了,还是不行

标签: laravel


【解决方案1】:

您实际上需要使用whereHas 来处理这个...

$items = UserItems::with('item')
        ->whereHas('item', function($q) {
            $q->where('type', 'shirt');
         })
        ->where('user_id','=',$this->id)
        ->where('quantity','>',0)
        ->get();

【讨论】:

    【解决方案2】:

    Decision

    试试:

    $items = UserItems::with(['item' => function($query){
        return $query->where("type", "shirt")
    })
    ->where('user_id','=',$this->id)
    ->where('quantity','>',0)
    ->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-05
      • 1970-01-01
      • 2021-09-25
      • 2015-07-05
      • 2014-06-12
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多