首页 > 解决方案 > 在 Eloquent 中使用第一个请求作为 where 子句的嵌套请求

问题描述

我有一个名为 Campaign 的模型,它属于另外两个模型“客户”和“优惠券”。

现在基于一个campaignId,我需要找到具有此Id 的活动,以及具有相同clientId 的其他活动。

我能够用 2 个请求完成它并合并结果,但我很确定它可以在一个请求中完成。

以防万一这是我的 2 个请求:

$couponDetails = Campaign::with(['coupon', 'client'])
                    ->where('uuid', '=', $campaignId)
                    ->get()
                    ->all();

$extraCoupon = Campaign::with(['coupon', 'client'])
                    ->where('client_id', '=', $couponDetails[0]->client_id)
                    ->whereNotIn('uuid', [$couponDetails[0]->uuid])
                    ->get()
                    ->all();

我想我应该在campaignId 上进行嵌套选择,然后在收到的clientId 上执行where 子句,但我找不到正确的语法。

谢谢您的帮助。

标签: laraveleloquent

解决方案


在 laravel 中有一个选项,orWhere它会给你这样的东西:

$coupons = Campaign::with(['coupon', 'client'])
    ->where(function($query) use ($campaignId){
        $query->where('uuid', '=', $campaignId);
    })
    ->orWhere(function($query) use ($couponDetails){
        $query->where('client_id', '=', $couponDetails[0]->client_id)
              ->whereNotIn('uuid', [$couponDetails[0]->uuid]);
    })
    ->get()
    ->all();

推荐阅读