简体   繁体   中英

Laravel Model Relationships

I am playing around with Laravel Models and i came across a fairly common database design pattern for which i am unable to establish relationships (using Laravel).

Here is the Database design

If we only take into consideration the following tables (for simplicity):
1.Customers
2.Products
3.Product_Prices (The products price is expected to change over time and we need to keep track)
4.Customer_Orders
5.Customer_Orders_Products (A customer can order multiple products in a single order)

Here is what i have so far:
1. Product HAS MANY Product_Prices
2. Product_Prices BELONGS TO Products
3. Customer HAS MANY Customer_Orders
4. Customer_Order BELONGS TO Customer
5. Customer_Order HAS MANY Customer_Order_Products
6. Customer_Order_Products BELONGS TO Customer_Order

I think that the Price for each Customer_Order_Products will be fetched by establishing a relationship to the Products table? How do we establish such a relationship?

How to get an Laravel Collection Object with the following details (I am not sure if only Eloquent returns a collection object or if its the same with Fluent ):
1. Customer WITH Customer_Orders WITH Customer_Orders_Products WITH Product_Price ?

Also how to put constrains like:
1. Customer WITH Customer_Orders WITH Customer_Orders_Products WITH Product_Price WHERE Product_Price < Customers_Order.date_order_placed ?

Thanks

I think de-normalizing the database to include the price in Customer_Order_Products and then use following relationship would be better idea.

class CustomerOrder {
    protected $table = 'Customer_Orders';

    ...

    public function products()
    {
        return $this->belongsToMany('Products')->withPivot('quantity','comments', 'price');
    }

    ...
}

In your case the Customer_Orders_Products isn't just a fancy join table, but a model of it's own with a relationship to the Product_Prices table.

Add a product_price_id to the table to map the ordered product to the price.

This adds flexibility (maybe the price is determined by volume later instead of 'recentness') at almost the same overhead cost as storing the price directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM