dongyuqie4322 2017-06-20 17:23
浏览 91
已采纳

带有参数数组的SQL请求

I have a problem with a SQL(dql) request, I have a table with Books(Media), a table with categories, and a table who associate the two: CategoryAffiliation (a book can have multiple categories)

In the Client side, i can choose to search for books by checking multiple categories. Then the client send a array of categories to the server and he must return the books who have at least one of those categories.

$books = [];
if (isset($data['categories'])) {
    foreach ($data['categories'] as $key => $value){
        $query = $em->createQuery("SELECT m
                                   FROM AppBundle:Media m, AppBundle:Category c, AppBundle:CategoryAffiliation mc
                                   WHERE m.idMedia = mc.idMedia
                                   AND mc.idCategory = :key
                                   GROUP by m.idMedia"
        )->setParameter('key',$key);
        $result = $query->getResult();
        foreach ($result as $book) {
            array_push($books, $book);
        }
    }
}

This is my solution for now but this is not great, i can't ORDER BY the result.. I receive an array of duplicates books, and then in the client side I merge them to delete the duplicates.

I am searching a way to have a single request to fetch all the data at once

Thanks

  • 写回答

1条回答 默认 最新

  • doutizhou5312 2017-06-20 17:43
    关注

    I don't have access to my stuff to test it but this could do it. I'm just not sure how setParameter will handle the fact that I put ' inside the string. I think that you will need to get the raw information. I can't remember how symfony and doctrine manage that, it's been too long ;)

    If you can't find an other way, you could build it in the string directly... which I don't really recommend.

    $query = $em->createQuery("SELECT m
                               FROM AppBundle:Media m, AppBundle:Category c, AppBundle:CategoryAffiliation mc
                               WHERE m.idMedia = mc.idMedia
                                     AND mc.idCategory IN (:key)
                               GROUP by m.idMedia"
            )->setParameter('key',implode("','",array_keys($data['categories'])));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 c语言,请帮蒟蒻看一个题
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)