Laravel将关系合并到一个表中



我有一个模型用户。它有两种关系方法。

public function destinationTransaction()
{
return $this->hasManyThrough(
Transaction::class,
Account::class,
'object_id',
'destination_id'
)->where('object_type', User::class);

和:

public function sourceTransaction()
{
return $this->hasManyThrough(
Transaction::class,
Account::class,
'object_id',
'source_id'
)->where('object_type', User::class);
}

它们之间的区别仅在于secondKey(destination_id和source_id(

我想创建方法事务,它将返回结果sourceTransactiondestinationTransaction

示例:

public function transaction()
{
$desTrn = $this->destinationTransaction;
$srTrn= $this->sourceTransaction;
// Merge collections and return single collection.
return $competitionsHome->merge($srTrn);
}

此方法不适用,因为它返回一个数组。

也许您可以以某种方式编写带有联接的查询?

transaction()方法中尝试联合(未测试(:

public function transaction()
{
return $this->destinationTransaction()->union($this->sourceTransaction()->toBase());
}

似乎users通过object_id有很多accountsaccounts通过source_iddestination_id有许多transactions,您想将这两者合并为一。

您可以使用join连接它们:

public function transaction() {
return Account::join('users', 'users.id', 'accounts.object_id')
->where('accounts.object_id', $this->id)
->where('accounts.object_type', User::class)
->join('transaction AS destination', 'destination.id', 'accounts.destination_id')
->join('transaction AS source', 'source.id', 'accounts.source_id')
// Now you can select the destination's columns and source columns with alias names:
->selectRaw('destination.*, source.column AS source_column, ...')
->get()
}

最新更新