Doctrine2: Best way to handle many-to-many with extra columns in reference table

后端 未结 14 1982
灰色年华
灰色年华 2020-11-22 10:44

I\'m wondering what\'s the best, the cleanest and the most simply way to work with many-to-many relations in Doctrine2.

Let\'s assume that we\'ve got an album like

14条回答
  •  有刺的猬
    2020-11-22 11:41

    Here is the solution as described in the Doctrine2 Documentation

    customer = $customer;
            $this->items = new ArrayCollection();
            $this->created = new \DateTime("now");
        }
    }
    
    /** @Entity */
    class Product
    {
        /** @Id @Column(type="integer") @GeneratedValue */
        private $id;
    
        /** @Column(type="string") */
        private $name;
    
        /** @Column(type="decimal") */
        private $currentPrice;
    
        public function getCurrentPrice()
        {
            return $this->currentPrice;
        }
    }
    
    /** @Entity */
    class OrderItem
    {
        /** @Id @ManyToOne(targetEntity="Order") */
        private $order;
    
        /** @Id @ManyToOne(targetEntity="Product") */
        private $product;
    
        /** @Column(type="integer") */
        private $amount = 1;
    
        /** @Column(type="decimal") */
        private $offeredPrice;
    
        public function __construct(Order $order, Product $product, $amount = 1)
        {
            $this->order = $order;
            $this->product = $product;
            $this->offeredPrice = $product->getCurrentPrice();
        }
    }
    

提交回复
热议问题