I'm trying to select specific columns from tables that I have joined using Eloquent.
I have 3 models - Transaction - Channel - Merchant
Transactions links to Channel. It has a hasOne relationship. Channel links to Merchant. It also has a hasOne relationship.
public function channel() {
return $this->hasOne(Channel::class, 'uuid', 'entityId');
}
public function merchant() {
return $this->hasOne('App\Merchant', 'uuid', 'sender');
}
I'm using eager loading so have the following in the Transaction model:
protected $with = ['channel'];
And Channel has:
protected $with = ['merchant']:
This the query I'm trying to convert into Eloquent but I'm unsure how to select columns when they belong to related models. What I don't get is that if the relationships have been defined, why can't I select columns from the other models without having to reuse joins or the with clause?
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;