【问题标题】:How replace join query with whereHas?如何用 whereHas 替换连接查询?
【发布时间】:2019-03-02 06:11:51
【问题描述】:

我使用的是 Laravel 5.6,我有一个标准查询

    Order::where('dict_statuses_id', 1)
->leftJoin('dict_statuses', 'dict_statuses_id', '=', 'dict_statuses.id')
->get();

所以我有详细的订单列表,其中状态 = 1(新)在加入表后我看到状态为新或完成。有什么方法可以使用 whereHas 更改此查询?

我试过了

Order::whereHas('status', function($q){
            $q->where('dict_statuses_id', 1);
        })->get();

但没有结果,在模型订单中我有

public function status()
    {
        return $this->hasMany('App\DictStatuses');
    }

[更新]

我有一个错误:

  Column not found: 1054 Unknown column 'dict_statuses.orders_id' 
in 'where clause' (SQL: select * from `orders` where exists 
(select * from `dict_statuses` where `orders`.`id` = `dict_statuses`.`orders_id` and `dict_statuses_id` = 1) 
and `orders`.`deleted_at` is null) 

在我的表中,我有表 Orders 字段:dict_statuses_id 和表 dict_statuses 字段:idpublic_name

为什么错误是关于 dict_statuses.orders_id

【问题讨论】:

    标签: php eloquent laravel-5.6


    【解决方案1】:

    尝试 Order::has('status')->get();

    【讨论】:

      【解决方案2】:

      您可以将变量传递给关系,这样您就有可能这样做。

      public function status($id) {
          return $this->hasMany(DictStatuses::class)->where('dict_statuses_id', $id);
      }
      

      尝试定义本地键和外键。

      $this->hasMany(DictStatuses::class, 'foreign_key', 'local_key');
      

      【讨论】:

      • 'dict_statuses_id' 在什么表上?
      • 这是表 dict_statuses 的键
      • 您是否尝试过手动定义关系中的本地和外键?
      • 好的,我在订单表中有:CONSTRAINT orders_ibfk_7 FOREIGN KEY (dict_statuses_id) REFERENCES dict_statuses (id) ON DELETE CASCADE 。可以吗?
      【解决方案3】:

      我认为您的 dict_statuses 没有名为 order_id 的列。

      请将该列包含在您的迁移中

      然后调用

      Order::whereHas('status', function($q){
              $q->where('dict_statuses_id', 1);
          })->get();
      

      在你的控制器中

      或将Order模型中的关系更改为

      public function status(){
       return $this->belongsTo('App\DictStatuses'):
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-02-12
        • 1970-01-01
        • 2016-07-22
        • 2023-03-07
        • 1970-01-01
        • 2018-03-22
        • 2014-12-02
        相关资源
        最近更新 更多