Eloquent 关系枢轴 table 与 table
Eloquent relation pivot table with table
我阅读了 laravel 文档,但我不是很理解。
我的数据库中有这个结构。
PriceTable - 其中包含有关促销价格和默认价格的时间段的信息。
产品 - 包含有关产品的信息。
和 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 |
并且在订单 table 我可以有多个产品,所以我想知道是否可以将订单 table 与枢轴 table [=26= 联系起来], 因为我需要的信息是table属于商品售出时的价格
首先你可以定义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');
}
}
价格表模型 (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;
}
我阅读了 laravel 文档,但我不是很理解。 我的数据库中有这个结构。
PriceTable - 其中包含有关促销价格和默认价格的时间段的信息。
产品 - 包含有关产品的信息。
和 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 |
并且在订单 table 我可以有多个产品,所以我想知道是否可以将订单 table 与枢轴 table [=26= 联系起来], 因为我需要的信息是table属于商品售出时的价格
首先你可以定义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');
}
}
价格表模型 (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;
}