PHP-Doctrine2: Items - Shops - ItemsAtShops - how to conveniently implement using Doctrine2?

我与影子孤独终老i 提交于 2019-12-12 10:12:12

问题


Somehow I can't figure out how to implement the following relations using Doctrine 2 syntax:

I have Items and Shops. Each item has different price and different quantity at each shop. So, I have Items table, Shops table and ItemsAtShops table. How do I reflect the last one in Doctrine?

I guess I need to create ItemsAtShops entity, relates ManyToOne -> Items and ManyToOne -> Shops, right? But in this case... how do I conveniently fetch a list of Items at the specific Shops with their prices and quantities at given Shops? So, that all these can be conveniently iterated?

I need to render a page with a list of Items and their Prices and Quantities at specific shops. There is a template for displaying Item there (with all it's subproperties - prices etc). So, it would be the most convenient to pass just one object to this template and iterate it and it's subobjects (if any) there.


回答1:


I struggle with this kind of scenario in Doctrine, as well. Rails had spoiled me with their has_many :through => relationship which makes this sort of thing trivial.

You are correct, you do need three entities: Shops, Items, ItemsAtShops using dual ManyToOne relationships.

I would assume that ItemsAtShop would look like:

class ItemsAtShop 
{        
   private $shop;
   private $items;
   private $quantity;
}

As far a querying goes, you'll need to rock the joins:

$queryBulder->select('ias')
            ->from(ItemsAtShop, 'ias')
            ->leftJoin('ias.Item', 'i')
            ->leftJoin('ias.Shop', 's')
            ->where('s.id = :shop_id')
            ->andWhere('i.price <= :my_price')
            ->orderBy('i.price', 'DESC');

Remember, when using DQL, you're usually querying entire Entity objects, which will fetch their relationships on their own. This should result in a collection of ItemsAtShop you can iterate over.

I might take some fidgeting to figure out the correct query. I'll often start with a SQL query I know works, and translate it into DQL.



来源:https://stackoverflow.com/questions/3185598/php-doctrine2-items-shops-itemsatshops-how-to-conveniently-implement-usin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!