laravel - Laravel - 使用 Eloquent 从连接关系模型中选择特定列
问题描述
我正在尝试从使用 Eloquent 加入的表中选择特定列。
我有 3 个模型 - 交易 - 渠道 - 商家
交易链接到频道。它有一个 hasOne 关系。渠道链接到商家。它也有一个 hasOne 关系。
public function channel() {
return $this->hasOne(Channel::class, 'uuid', 'entityId');
}
public function merchant() {
return $this->hasOne('App\Merchant', 'uuid', 'sender');
}
我正在使用急切加载,因此在事务模型中有以下内容:
protected $with = ['channel'];
频道有:
protected $with = ['merchant']:
这是我试图转换为 Eloquent 的查询,但我不确定当它们属于相关模型时如何选择列。我没有得到的是,如果已经定义了关系,为什么我不能从其他模型中选择列而不必重用连接或 with 子句?
SELECT SUM(t.amount) AS amount,
m.name
FROM transactionsV2 t JOIN
channels c
ON t.entityId = c.uuid JOIN
merchants m
ON c.sender = m.uuid
WHERE t.paymentType = 'DB' AND
t.status = 1 AND
t.processing_time >= '2019-01-01' AND
t.processing_time < '2019-01-21'
GROUP BY m.name;
解决方案
你可以尝试这样的事情:
Transaction::sum('amount')
->whereStuf(...)
->with(['channel.merchant' => function($query){
$query->select('name')
->groupBy('name');
}])->get();
channel.merchant
允许您获取嵌套关系。
推荐阅读
- unit-testing - 使用 Mokito 对登录页面进行 junit 测试
- html - 纯 CSS 加载指示器适合容器大小
- reactjs - TS2339:“EventTarget”类型上不存在“最近”属性。- 如何在 React 中获取原生 event.target?
- gitversion - GitVersion 配置文件中的默认模式
- python - 使用python烧瓶应用程序部署到heroku时Procfile / wsgi出现问题〜找不到属性
- labview - 从 LabVIEW 2018 创建表时的 SQL Server 数据库表列大小限制问题
- javascript - React-native 在导入语句上抛出意外的令牌错误
- python-3.x - 由于包装错误,无法安装需求文件
- android - android TextInputLayout.class.getDeclaredField("mErrorView") 抛出异常
- php - 每个用户的WordPress自定义菜单?