Sort relationship "Many To Many" using as base field another table

4

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:

  • Simple: Simple products that have only one price;
  • Grouped: Products without price because they are just a grouping of others products, each with its price. Used when a product has various presentations;
  • Child: Products that are part of a product grouped. They have a price, but are not displayed alone. These products are only displayed within Grouped products of the which are part of it.
  • 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.

        
    asked by anonymous 09.05.2014 / 17:46

    2 answers

    1

    See if it helps:

    How to order using Eloquent:
    link

    Select the first 10 lines:
    link < br>
    How to get the first record with laravel:
    link

        
    20.08.2014 / 19:43
    0

    I think in this case it would be nice to save a timestamp until you know when that price was placed and help you in sorting ... put created_at in the price table. Take advantage and stay the hint of putting some tables in there a field of creation and another of modification until you have a better control ...

        
    10.05.2014 / 03:59