【问题标题】:Laravel has Many with a where on upper modelLaravel 在上层模型上有很多带有 where 的地方
【发布时间】:2014-09-25 21:47:02
【问题描述】:

我有以下结构


转弯
身份证

订单支付
身份证
turn_id
invoice_id

订单发票
身份证
order_id

订购
身份证
取消
合并


我想要做的是得到OrderPayments,其中Order既没有取消也没有合并

现在我依次有以下代码

class Turn{

    public function orderPayments(){
        return $this->hasMany('OrderPayment');
    }
}

我应该怎么做才能只获得与Order 相关的付款

 ->where('canceled' < '0000-00-00 00:00:10 ')
 ->where('merged'  < '0000-00-00 00:00:10 ')

非常感谢!!


EDIT 更新我实际拥有的关系

OrderPayment我有函数

public function invoice(){
    return $this->belongsTo('Invoice');
}

OrderInvoice我有函数

public function order(){
    return $this->belongsTo('Order');
}

这是我在Turn 上尝试的代码如下

public function orderPayments(){
    return OrderPayment::whereHas('invoice',function($query){
       $query->whereHas('order',function($query){
           $query->where('canceled','<','0000-00-00 00:00:01')
                 ->where('merged','<','0000-00-00 00:00:01');
       });
    })->where('turn_id','=',$this->id)->get();
}

我得到以下异常

Call to undefined method Illuminate\Database\Query\Builder::order()

【问题讨论】:

    标签: php mysql laravel eloquent


    【解决方案1】:

    你需要whereHas:

    $payments = OrderPayment::whereHas('invoice', function ($q) {
       $q->whereHas('order', function ($q) {
          $q->where('canceled', '=', '0000-00-00')
            ->where('merged', '=', '0000-00-00');
       });
    })->get();
    

    作为旁注,我会将这些列更改为 nullable 并搜索 whereNull('canceled') 等。

    【讨论】:

    • 嘿,非常感谢您的回答,但是我在尝试 Call to undefined method Illuminate\Database\Query\Builder::Order() 时收到此错误我认为 orderInvoices 是获取付款发票的方法对吗?在我的情况下,该功能称为发票,所以我假设 order 是 Molde OrderInvoice 上获取订单的方法?这叫订单
    • 刚刚用更多信息更新了问题,我添加了我在每个模型中的关系方法以及我现在正在尝试的方法,感谢您的回答
    • 知道为什么会这样吗?
    • 您的代码真的很难阅读。你有OrderInvoice模型,那么你在OrderPayment的关系中引用Invoice。如果你的关系是正确的,那么这个错误就不会出现。我用invoice 编辑了我的答案,但这就是你所尝试的......
    • 是的,在关系函数中,我删除了Order 部分......你认为我可能是问题吗?
    猜你喜欢
    • 2023-02-24
    • 2021-11-20
    • 2019-03-21
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 2021-05-31
    • 2015-06-27
    • 2021-01-28
    相关资源
    最近更新 更多