laravel - 在 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 子句,但我找不到正确的语法。
谢谢您的帮助。
解决方案
在 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();
推荐阅读
- vue.js - "Mustache" syntax alternative for Vue template when using Pug language
- python - Scrapy startproject 不起作用权限被拒绝:蜘蛛
- amazon-web-services - 为什么我无法从我的 PC 连接到新的 AWS Aurora Serverless 实例?
- excel - 如何按颜色对表格列进行排序?
- html - 如何在表格边界内对齐文本输入元素?
- python - 枚举 Pandas 数据框后,字典条目都相同
- python - Django & Celery - 跨多个方法和文件发送信号
- typescript - Firebase 数据库出现意外令牌错误
- c# - Microsoft.EntityFrameworkCore ProjectTo() 找不到我的存储库的方法定义
- python - Python - Beautifulsoup - 从列表中传递单个 url 以被抓取