我对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:??’)->??
请提供任何帮助,我们将不胜感激,谢谢您抽出时间。
假设实体名为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
}
有关完整参考,请参阅使用条令文件中的对象。
我希望这对你有帮助
如果你需要更精确的信息或任何其他信息,请毫不犹豫地发表评论。
编辑
要访问对象的属性,请使用其getters:
$cartView = array(
'products' => $cart->getProducts(), // return the property $products
'user' => $cart->getUser(), // return the property $user
);
只有当这些方法存在并且具有公共访问权限时,这才有可能实现。
注意在使用Symfony这样的框架之前,您应该更多地研究OOP并进行实践。