5
I am making a virtual store, to know better the Laravel framework, and I came across the following situation:
I have a table called products to store product-related information. I also have a table called types to store product types. I also have a table called prices, to store the prices of the products - I have separated the prices to be able to have a history of changing prices of the products.
There are three types of products:
- Simple: Simple products, which have only one price;
- Grouped: Products without price, as they are only a grouping of others products, each with its own price. Used when a product has several presentations;
- Child: Products that are part of a product grouped. Have price, but are not displayed alone. These products are only displayed within Grouped type products of which are part.
I use the Children table to relate the products table to itself. This way, I can relate the products of type Child and Grouped.
Follow the database diagram:
The models are listed as follows:
Product belongsTo Type
Product belongsToMany Product
Product hasMany Price
The problem occurs when I try to recover the price of Child-type products from a Grouped product. This information comes in the form of an Eloquent Collection, with all the products that are part of this product grouped in the order of insertion. I’d like to sort them out for the price, but the fact that this information is on another table made it difficult. The closest I could get to the desired result was modifying the method of the relationship between the Product class and itself. Follow the code:
public function children(){
return $this->belongsToMany('Product', 'children', 'father_id', 'child_id')->join('prices', 'child_id', '=', 'product_id')->orderBy('value');
}
However, this repeats some values, since it does not bring only the last inserted price.
These fields are not in the diagram, but I created them in the Laravel Migrations.
– João Eduardo