mysql - 如何将此查询转换为 doctrine DQL

标签 mysql symfony doctrine-orm dql doctrine-query

SELECT apntoken,deviceid,created 
FROM `distribution_mobiletokens` as dm
WHERE userid='20'
and not exists (
    select 1 
    from `distribution_mobiletokens`
    where userid = '20'
    and deviceid = dm.deviceid
    and created > dm.created
    )

此查询所做的是选择用户 ID 等于 20 且设备 ID 相同但为设备选择最新的 apntoken 的所有移动 token 。

我的数据库如下所示。

enter image description here

有关此查询的更多信息,我从我在此处提出的另一个问题 (How to group by in SQL by largest date (Order By a Group By)) 中得到了这个答案

我尝试过的事情

$mobiletokens = $em->createQueryBuilder()
          ->select('u.id,company.id as companyid,user.id as userid,u.apntoken')
          ->from('AppBundle:MobileTokens', 'u')
          ->leftJoin('u.companyId', 'company')
          ->leftJoin('u.userId', 'user')
          ->where('u.status = 1 and user.id = :userid')
          ->setParameter('userid',(int)$jsondata['userid'])
          ->groupby('u.apntoken')
          ->getQuery()
          ->getResult();

       //@JA - Get the list of all the apn tokens we need to send the message to.
       foreach($mobiletokens as $tokenobject){
           $deviceTokens[] = $tokenobject["apntoken"];
           echo $tokenobject["apntoken"]."\n";
       }

        die();

这给了我不正确的响应

63416A61F2FD47CC7B579CAEACB002CB00FACC3786A8991F329BB41B1208C4BA
9B25BBCC3F3D2232934D86A7BC72967A5546B250281FB750FFE645C8EB105AF6
latestone

在此感谢任何帮助!

其他信息

带有 SELECT * FROM 的数据

enter image description here

使用我在顶部提供的 SQL 后的数据。

enter image description here

最佳答案

您可以使用通过查询生成器创建的子选择作为示例:

public function selectNewAppToken($userId)
{
    // get an ExpressionBuilder instance, so that you
    $expr = $this->_em->getExpressionBuilder();

    // create a subquery in order to take all address records for a specified user id
    $sub = $this->_em->createQueryBuilder()
        ->select('a')
        ->from('AppBundle:MobileTokens', 'a')
        ->where('a.user = dm.id')
        ->andWhere('a.deviceid = dm.deviceid')
        ->andWhere($expr->gte('a.created','dm.created'));


    $qb = $this->_em->createQueryBuilder()
        ->select('dm')
        ->from('AppBundle:MobileTokens', 'dm')
        ->where($expr->not($expr->exists($sub->getDQL())))
        ->andWhere('dm.user = :user_id')
        ->setParameter('user_id', $userId);

    return $qb->getQuery()->getResult();
}

关于mysql - 如何将此查询转换为 doctrine DQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43078404/

相关文章:

php - 如何将 Doctrine ORM 默认跟踪策略更改为 Deferred Explicit

PHP/PDO SQLSTATE[42000] : Syntax error or access violation: 1064 Nightmare

python - 使用 xml "map"通过 python 将数据导入 MySQL?

mysql - 在多线程中使用同一个数据库连接时,后面发生了什么?

php - Symfony 2.5 - 数据转换器和 View 转换器

Symfony2 : choice without empty value

MySQL 5.1 不允许我使用 declare in limits。我尝试了所有替代方法,但没有任何效果,我无法更新 MYSQL 版本

doctrine-orm - 交响乐与学说 : Optional foreign key

php - 学说2,十进制只能包含14位数字

php - 在 Symfony 项目上使用 "Class Table Inheritance"加入 Doctrine 太多