I read the laravel documentation but I couldn’t understand very well. I have this structure on my database.
PriceTable – which contains info about the period of promotional prices and the default price.
Product – which contains info about products.
and PriceTable_Product – which contains the foreign keys of Product and PriceTable and the respective price.
Example:
PriceTable | PriceTable_Product | Product id | description | PriceTable_id | Product_id | price | product_id| name 1 | default | 1 | 1 | 5.00 | 1 | test 2 | promotional | 2 | 1 | 3.50 |
And at the Order table I can have multiples products, so I want to know if it is possible to relation Order table, with the pivot table PriceTable_Product, because I need the information of which table belongs the price when the product was sold.
Advertisement
Answer
First of all you may define the relations between Product and PriceTable.
Product model (AppProduct.php)
<?php namespace App; class Product extends Model { protected $table = 'products'; //if the default primary key isn't 'id' you may use $primaryKey protected $primaryKey = 'product_id'; public function pricetables() { return $this->belongsToMany('AppPriceTable'); } }
PriceTable model (AppPriceTable.php)
<?php namespace App; class PriceTable extends Model { protected $table = 'pricetable'; public function products() { return $this->belongsToMany('AppProduct'); } }
If you created the relations then you can use:
$product = AppProduct::find(1); foreach ($product->pricetables as $pricetable) { echo $pricetable->pivot->description; }