首页 > 解决方案 > 创建间接关系并返回两个关系的总和

问题描述

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

用户表

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;

标签: laravel-5eloquentrelationship

解决方案


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

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

推荐阅读