【问题标题】:Create indirect relationships and return the sum of two relationships创建间接关系并返回两个关系的总和
【发布时间】:2019-09-26 11:08:35
【问题描述】:

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

用户表

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-5 eloquent relationship


    【解决方案1】:

    以下是您如何简单地实现合并关系

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

    【讨论】:

    • 感谢您的回复,解决了一半的问题。现在我只需要能够检索 conversationsSeller 关系。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多