雄辩的关系透视表与表


Eloquent relation pivot table with table

我读了laravel文档,但我不能很好地理解。我的数据库中有这个结构

PriceTable—包含促销价格期间和默认价格的信息。

Product -包含有关产品的信息。

和PriceTable_Product—其中包含Product和PriceTable的外键以及各自的价格。

的例子:

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  |

在Order表中,我可以有多个产品,所以我想知道是否有可能将Order表与数据透视表PriceTable_Product联系起来,因为我需要产品销售时哪个表属于价格的信息。

首先你可以定义Product和PriceTable之间的关系。

产品模型(App ' Product.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('App'PriceTable');
    }
}

PriceTable model (App'PriceTable.php)

<?php
namespace App;
class PriceTable extends Model {
    protected $table = 'pricetable';
    public function products() {
        return $this->belongsToMany('App'Product');
    }
}

如果你创建了关系,那么你可以使用:

$product = App'Product::find(1);
foreach ($product->pricetables as $pricetable) {
    echo $pricetable->pivot->description;
}