symfony中的ORM错误

时间:2017-07-27 10:31:26

标签: php symfony orm

如果使用此代码

,我在显示symfony列表时会有些奇怪
 $products = $em->getRepository('AppBundle:Product')->findBy(["id" => array(3)]);
dump($products);
exit;

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

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 ▶}
  }
]

但如果我使用此代码

$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)。这只会显示一个错误的类别。

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 ▶}
  }
]

1 个答案:

答案 0 :(得分:0)

如果你需要通过Id(只有一个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;