首页 > 解决方案 > 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;

标签: laravellaravel-5eloquent

解决方案


你可以尝试这样的事情:

Transaction::sum('amount')
    ->whereStuf(...)
    ->with(['channel.merchant' => function($query){
        $query->select('name')
            ->groupBy('name');
    }])->get();

channel.merchant允许您获取嵌套关系。


推荐阅读