创建间接关系并返回两个关系的总和

时间:2019-09-26 11:08:35

标签: laravel-5 eloquent relationship

我有一个程序可以在人与人之间共享服务。基本上,我在尝试获取用户之间的对话时遇到了问题。这里是想法: 我的程序允许用户向其他用户提供服务,也可以从其他用户获取服务。每个用户可以注册无限数量的服务。 当用户找到他/她想要获得的服务时,他会创建交易并开始与对方进行对话。 表的结构如下(我仅包括关系列):

用户表

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 );
    }

我也想创建对话seller()函数

    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;

1 个答案:

答案 0 :(得分:0)

这是您简单地实现合并关系的方法

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);
}