php - Merge 2 queries in 1 Doctrine DQL -
i'm using doctrine 2.4 symfony 2.8 , i'm trying build friendship system.
i have materelationship entity :
class materelationship { /** * @var integer * * @orm\column(type="integer", name="id") * @orm\id * @orm\generatedvalue(strategy="auto") */ private $id; /** * @orm\manytoone(targetentity="acme\userbundle\entity\user") * @orm\joincolumn(name="sender", referencedcolumnname="id", nullable=false) * */ private $sender; /** * @orm\manytoone(targetentity="acme\userbundle\entity\user") * @orm\joincolumn(name="receiver", referencedcolumnname="id", nullable=false) * */ private $receiver; /** * @var \datetime * * @orm\column(type="datetime", nullable=false) */ private $date; /** * @var boolean * * @orm\column(type="boolean", nullable=false) */ private $invitationaccepted;
my goal make dql query accepted friends relationship given user (no matter if user sender or receiver) .
i managed 2 queries , merging results, it's not optimized , it's harder implement $limit
way.
public function getmates($user, $limit = 0){ $query1 = $this->_em->createquery('select m, u.nickname, u.username acmeuserbundle:materelationship m join m.receiver u m.invitationaccepted = 1 , m.sender = :user') ->setparameter('user', $user); try{ $result1 = $query1->getresult(); } catch(\doctrine\orm\noresultexception $e){ $result1 = []; } $query2 = $this->_em->createquery('select m, u.nickname, u.username acmeuserbundle:materelationship m join m.sender u m.invitationaccepted = 1 , m.receiver = :user') ->setparameter('user', $user); try{ $result2 = $query2->getresult(); } catch(\doctrine\orm\noresultexception $e){ $result2 = []; } return array_merge($result1, $result2); }
i'd have single query use ->setmaxresults($limit)
have no idea how merge these 2 queries in 1. :)
here's proposal using doctrine query builder
public function getmates($user, $limit = 0) { // create query builder $querybuilder = $this->_em->getrepository("acmeuserbundle:materelationship")->createquerybuilder('m'); // create 'or' expression $or = $querybuilder->expr()->orx(); $or ->add('m.sender = :user') ->add('m.receiver = :user'); // create query $querybuilder ->andwhere('m.invitationaccepted = 1') ->andwhere($or) ->setmaxresults($limit) ->setparameter('user', $user); // return result return $querybuilder->getquery()->getresult(); }
Comments
Post a Comment