问题
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