Skip to content

Instantly share code, notes, and snippets.

@ajcastro
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajcastro/6a335c60a2053fdbcebb to your computer and use it in GitHub Desktop.
Save ajcastro/6a335c60a2053fdbcebb to your computer and use it in GitHub Desktop.
Laravel Eloquent Custom Polymorphic Table Relations

Laravel Eloquent Polymorphic Table Relations

Consider this tables: products and product_settings.

Table products

id name
1 Laptop
2 Tablet

Table product_settings

id product_id effectivity_date price
1 1 2015-06-07 25,000.00
2 1 2015-07-07 23,000.00

Base from the tables, it is obvious that the example relationship is Product hasMany ProductSetting. But, we also need to access the currenSetting of a product based from the effectivity_date of the product. This relationship is achievable, look at the example below. The relationship can also be eager-loaded.


class Product 
{
  public function settings() 
  {
    return $this->hasMany('ProductSetting');
  }
  
  public function currentSetting() 
  {
     $currentDate = date('Y-m-d');

        $joinerSql = "
            (
                SELECT 
                product_id, max(effectivity_date) as max_date
                FROM product_settings
                where effectivity_date <= '{$currentDate}'
                group by product_id
            ) as joiner
        ";

        $onSql = "
            joiner.max_date   = product_settings.effectivity_date and 
            joiner.product_id =  product_settings.product_id
        ";

        return $this->hasOne('ProductSetting')
            ->select('product_settings.*')
            ->join(
                \DB::raw($joinerSql),
                \DB::raw(""),
                \DB::raw($onSql),
                \DB::raw("")
            );
  }
  
}

Reference

Thanks from this site: http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment