laravel-5 - 创建间接关系并返回两个关系的总和
问题描述
我有一个程序可以在人们之间共享服务。基本上,我在尝试获取用户之间的对话时遇到了问题。想法是这样的:我的程序允许用户向其他用户提供服务,也可以从其他用户那里获取服务。每个用户可以注册无限数量的服务。当用户找到他/她想要获得的服务时,他会创建交易并开始与对方对话。我的表的结构如下(我只包括关系列):
用户表
id // This is the user identifier
服务表
id // This is the service identifier
user_id // This is the identifier of the user who created the service
交易表
id // This is the deal identifier
user_id // This is the identifier of the user acquiring the service
service_id // This is the identifier of the service being acquired in this deal
对话表
id // This is the identifier of the conversation
deal_id // This is the identifier of the deal that the conversation belongs to
这是我的问题:我希望能够检索每个用户的对话,无论是作为申请人还是作为卖家。
User.php
我为用户获取服务的对话创建了这种关系(在 中):
public function conversationsApplicant(){
return $this->hasManyThrough( Conversations::class, Deal::class );
}
我还想创建 conversationsSeller() 函数
public function conversationsSeller(){
return $this->????;
}
我猜我应该在Service.php
. 会是这样的$this->services()->with( 'deals' )->with( 'conversations' );
最终目标是有一种方法可以在一个中返回两种关系$user->conversations()->get()
。
public function conversations(){
return $this->conversationsApplicant() + $this->conversationsSeller();
}
为了检索关系,我在想也许有一个使用 SQL 查询的解决方法,但我不确定这是否会返回我需要的关系。这是我需要执行的查询:
SELECT
conversations.*
FROM
mydb.conversations, mydb.services, mydb.users, mydb.deals
WHERE
users.id = services.user_id AND
services.id = deals.service_id AND
deals.id = conversations.deal_id AND
users.id = $user->id;
解决方案
这是您如何简单地 实现合并关系的方法
public function getCombinedChats($value)
{
// There two calls return collections
// as defined in relations.
$Applicant= $this->conversationsApplicant;
$Seller= $this->conversationsSeller;
// Merge collections and return single collection.
return $Applicant->merge($Seller);
}
推荐阅读
- wpf - WPF Listbox 绑定到对象的子属性列表
- android - 如何在 Android Studio 中将弹出菜单添加到 android 桌面上的应用程序图标?
- node.js - 使用nodejs缩放图像并将结果保存到文件
- c - 数据类型的最小大小是以位还是字节定义的?
- python - 循环遍历python中的顺序列标题
- wordpress - 出现在我的 wordpress 网站顶部的代码行
- regex - DXL 正则表达式范围
- java - SpringBoot - 仅当使用 @ConditionalOnProperty 定义某个属性时才运行 @Configuration
- python-3.x - 如何在 Python Selenium WebDriver 中上传没有输入元素的文件
- python - __dict__ 和 __weakref__ 是类定义中的默认插槽吗?