Symfony中的ORM错误 [英] ORM bug in symfony

查看:112
本文介绍了Symfony中的ORM错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果使用此代码,我在显示symfony列表时有些奇怪

I have something weird in displaying the list of symfony if use this code

 $products = $em->getRepository('AppBundle:Product')->findBy(["id" => array(3)]);
dump($products);
exit;

我手动添加了一个id数组(3).它会显示我的类别列表,这是正确的

I manually add an id array(3). It display the list of my categories which is correct

array:1 [▼
  0 => Product {#2939 ▼
    #id: 3
    #name: "test"
    #title: "Test"
    #categories: PersistentCollection {#2941 ▼
      -snapshot: []
      -owner: Product {#2939}
      -association: array:20 [ …20]
      -em: EntityManager {#355 …11}
      -backRefFieldName: null
      -typeClass: ClassMetadata {#2450 …}
      -isDirty: false
      #collection: ArrayCollection {#2942 ▼
        -elements: []
      }
      #initialized: false
    }
    #status: 1
    #scheduleAt: DateTime {#2936 ▶}
  }
]

但是如果我使用了这段代码

but if I used this code

$em = $this->getEntityManager();
//product_id will generate value array
// result array(3)
$product_id = $em->getRepository('AppBundle:Product')->findCategoryById($id);
$products = $em->getRepository('AppBundle:Product')->findBy(["id" => $product_id]);

$ product_id的值是array(3).这只会显示一个错误的类别.

the value of $product_id is array(3). This will only display one category which is wrong.

array:1 [▼
  0 => Product {#2939 ▼
    #id: 3
    #name: "test"
    #title: "Test"
    #categories : PersistentCollection {#2941 ▼
      -snapshot: array:1 [ …1]
      -association: array:20 [ …20]
      -em: EntityManager {#355 …11}
      -backRefFieldName: null
      -typeClass: ClassMetadata {#2450 …}
      -isDirty: false
      #collection: ArrayCollection {#2942 ▼
        -elements: array:1 [▼
          0 => Category {#2684 ▶}
        ]
      }
      #initialized: true
    }
    #status: 1
    #scheduleAt: DateTime {#2936 ▶}
  }
]

推荐答案

如果您需要按ID查找(只有一个ID):

If you need to find by Id (only one Id):

$product = $em->getRepository('AppBundle:Product')->find(3);// Here return only one object if exist in Db;

如果需要使用where in:

$qb = $em->createQueryBuilder();
$qb->select('m');
$qb->from('AppBundle:Product', 'm');
$qb->where($qb->expr()->in('m.id', array(1,2,3,4,12,10)));


$result = $qb->getQuery()->getResult(); //Here return ArrayCollection
dump($result);
exit;

或在DQL中:

SELECT m FROM AppBundle:Product m WHERE m.id IN(1, 2, 3, 4, 5, 6, 12, 10)

最后一次查询:

$products = $em->getRepository('AppBundle:Product')->findById([1,2,3,4,5,6, 12,10]);
dump($products);
exit; 

这篇关于Symfony中的ORM错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆