【问题标题】:How to join two entity methods as one如何将两个实体方法合并为一个
【发布时间】:2020-01-25 00:21:08
【问题描述】:

基于一个私人消息应用程序,我的用户实体目前有两种方法来检索消息:

一个用来获取用户发送的消息

/**
 * @ORM\OneToMany(targetEntity="App\Entity\MessagePrive", mappedBy="emetteur")
 */
private $messagesPrivesEmis;

/**
 * @return Collection|MessagePrive[]
 */
public function getMessagesPrivesEmis(): Collection {
    return $this->messagesPrivesEmis;
}

和另一个获取从其他用户收到的消息

/**
 * @ORM\OneToMany(targetEntity="App\Entity\MessagePrive", mappedBy="recepteur")
 */
private $messagesPrivesRecus;

/**
 * @return Collection|MessagePrive[]
 */
public function getMessagesPrivesRecus(): Collection {
    return $this->messagesPrivesRecus;
}

第一种方法获取emetteur等于用户ID的消息,而第二种方法获取recepteur等于用户ID的消息。两者都是 Symfony 默认方法

是否可以“合并”这两种方法,以便在一个查询中获取用户发送和接收的所有消息?
还是我应该求助于自定义 DQL?

【问题讨论】:

    标签: php symfony methods


    【解决方案1】:
    public function getMerged(): Collection {
       return new ArrayCollection(
           array_merge(this->messagesPrivesEmis->toArray(), $this->messagesPrivesRecus->toArray())
       );
    }
    

    【讨论】:

    • 这是一种方法,但有两个问题。首先,消息没有排序。其次,它进行两次查询。不过谢谢,很高兴知道这一点
    • 恕我直言,合并这两个变量不是实体工作,而是使用一些实用程序类来合并两个集合函数 Merge (Collecion $a, Collection $b)
    • 我明白了,我想我将不得不做一个自定义查询。想确定一下,谢谢
    猜你喜欢
    • 1970-01-01
    • 2022-07-21
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多