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条数据。
但是这样写感觉代码怪怪的。请问还有更好的实现办法么。 或者上面代码能怎么优化。

《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 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年前 评论

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