ORM whereHas + with ?

 return $this->couponPromotion
            ->where('user_id', $user_id)
            ->whereHas('coupons', function ($query) use ($country_id) {
                $query->where('country_id', $country_id);
            })
            ->with(['coupons' => function ($query) use ($country_id) {
                $query->where('country_id', $country_id)
                    ->select([
                        'id',
                        'user_id',
                        'product_title',
                    ]);
            }])
            ->orderBy('id', 'desc')
            ->paginate($page_size, null, 'page', $page);

从couponPromotion查出了 3条数据,但是有1条数据 coupons 为null .现在只要取coupons不为null的记录, 通过whereHas 过滤了 。能取到了 想要的2条数据。
但是这样写感觉代码怪怪的。请问还有更好的实现办法么。 或者上面代码能怎么优化。

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 4

等。。。。

7年前 评论

with 里面的
->where('country_id', $country_id)
是不是可以省略掉?

7年前 评论

@Ken 是的 我就说怎么看着奇怪!


        return $this->couponPromotion
            ->where('user_id', $user_id)
            ->whereHas('coupons', function ($query) use ($country_id) {
                $query->where('country_id', $country_id);
            })
            ->with(['coupons' => function ($query) {
                $query->select([
                    'id',
                    'user_id',
                    'product_title',
                ]);
            }])
            ->orderBy('id', 'desc')
            ->paginate($page_size, null, 'page', $page);

这样就舒服多了。 自己应该想到的。

7年前 评论

不能去掉 如果是一对多的情况

6年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!