I am doing a virtual store, to know better the framework Laravel, and I came across the following situation:
I have a table called products to store the information related to the products. I also have a table named types to store the types of products. I also have a table called prices, to store the prices of the products - I have separated the prices in order to have a history of changing the prices of the products.
There are three types of products:
I use the children table to relate the table to itself. That way, I can relate Child and Grouped products.
Follow the diagram for the database:
The templates are listed as follows:
Product belongsTo Type
Product belongsToMany Product
Product hasMany Price
The problem occurs when I try to retrieve the price of Child products of a Grouped product. This information comes in the form of an Eloquent Collection, with all products that are part of this grouped product, in the order of insertion. I would like to sort them by price, but the fact that this information is on another table made this difficult. The closest I got to the desired result was to modify the method of the relationship between the Product class and itself. Here is 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 only bring the last price entered.