php - phpdoctrine save collection of differents entities -
i have interface:
interface product { function getamount(); }
and php doctine entities:
/** * @orm\table(name="orders") * @orm\entity */ class order { private $products = array(); public function addproduct(product $product){ $this->products[] = $product; } public function getproducts() { return $this->products; } function getamount() { $amount = 0; foreach ($this->products $product) { $amount += $product->getamount(); } return $amount; } } /** * @orm\table(name="books") * @orm\entity */ class book implements product { function getamount() { return 1; } } /** * @orm\table(name="pens") * @orm\entity */ class pen implements product { function getamount() { return 2; } }
book, pen - different entities , table. how implement relationship order::products collection of books, pens, etc(for save in database)?
i understand 2 solutions problem. first when saving(and loading) database manually convert relationship map(array of entities names , ids). decision not like. , second correct architecture. not know how. have ready-made solution ... please.
i'am not sure can way.
whether define separate entity poduct , add column product_type tell whether book, pen or ever.
in entity product property should defined enum , can tricky(depends on use besides doctrine)
or make each product type (what can pretty fast nightmare). i'd guess have manytomany relation. should smth. that.
in order
/** * @manytomany(targetentity="book") * @jointable(name="order_book", * joincolumns={@joincolumn(name="book_id", referencedcolumnname="id")}, * inversejoincolumns={@joincolumn(name="order_id", referencedcolumnname="id")} * ) */ protected $book; /** * @manytomany(targetentity="pen") * @jointable(name="order_pen", * joincolumns={@joincolumn(name="pen_id", referencedcolumnname="id")}, * inversejoincolumns={@joincolumn(name="order_id", referencedcolumnname="id")} * ) */ protected $pen;
and in book:
/* * @manytomany(targetentity="order", mappedby="book") */ protected $order;
with pen , others same way.
Comments
Post a Comment