我是Symphony的总菜鸟,但我正在努力学习。文档无法帮助我解决我遇到的这个特定问题。
我该怎么做:
// if ($products are in userCart) {
// show those only
// }
我正在努力寻找获取这些信息的方法。我尝试了很多次尝试。
我成功将产品刷新到数据库,我的关联如下:
我想在showCartAction
函数中执行此操作:
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
//then get the specific products
$products = $em->getRepository(‘ShopBundle:??’)->??
请感谢您的帮助,谢谢您的时间。
答案 0 :(得分:1)
假设该实体名为Product
:
// Your model, you can use it to fetch products
$productRepository = $em->getRepository('ShopBundle:Product');
// Retrieve all products as an array of objects
$products = $productRepository->findAll();
// Retrieve a specific product as object from its reference (id)
$product = $productRepository->find(1); // Returns product with 'id' = 1
// Retrieve a specific product based on condition(s)
$product = $productRepository->findOneBy(['price' => 10]);
// Retrieve many products based on condition(s)
$products = $productRepository->findBy(['price' => 10]);
检查特定产品是否在UserCart
对象中:
$cartRepository = $em->getRepository('ShopBundle:UserCart');
// Fetches the cart by its owner (the current authenticated user)
// assuming UserCart has a $user property that represents an association to your User entity
$cart = $cartRepository->findOneBy(['user' => $this->getUser()]);
// Check if a specific product is in the cart,
// assuming $product is a Product object retrieved like shown above
if ($cart->contains($product)) {
// Do something
}
有关整个参考,请参阅Doctrine文档中的Working with objects。
我希望这会对你有所帮助 如果您需要更多精确度或任何其他信息,请随时发表评论。
修改强>
要访问对象的属性,请使用其getter:
$cartView = array(
'products' => $cart->getProducts(), // return the property $products
'user' => $cart->getUser(), // return the property $user
);
只有方法存在且具有公共访问权限时才可行。
注意在使用像Symfony这样的框架之前,你应该更多地关注OOP并练习它。