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'])));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算