Laravel 自定义透视表中的雄辩关系
我可能把事情搞得太复杂了,但以下是我试图用雄辩的语言(Laravel 5)描述的关系: 我有一份产品清单和价目表。每种产品都可以有许多价目表。这很容易做到,但还有一件事-对于每个产品价目表分配,我可以根据数量确定许多价格,因此如下所示:Laravel 自定义透视表中的雄辩关系,laravel,laravel-5,Laravel,Laravel 5,我可能把事情搞得太复杂了,但以下是我试图用雄辩的语言(Laravel 5)描述的关系: 我有一份产品清单和价目表。每种产品都可以有许多价目表。这很容易做到,但还有一件事-对于每个产品价目表分配,我可以根据数量确定许多价格,因此如下所示: productID: 1010 priceListId: 1 min quantity: 1 -> price 10.00 min quantity: 5 -> price 9.50 min quantity: 10 -> price 9.0
productID: 1010
priceListId: 1
min quantity: 1 -> price 10.00
min quantity: 5 -> price 9.50
min quantity: 10 -> price 9.00
productID: 1010
priceListId: 2
min quantity: 1 -> price 15.00
min quantity: 40 -> price 14.00
min quantity: 90 -> price 12.00
我想我知道如何创建自定义透视表,尽管我不知道如何使用它。我现在不确定我的代码是否正确以及如何使用它
目前我有:
产品型号:
类产品扩展模型{
公共函数价格表()
{
返回$this->belongtomany('PriceList');
}
公共函数newPivot(模型$parent,数组$attributes,$table,$exists)
{
如果($PriceList的父实例)
{
返回新的ProductPricePivot($parent、$attributes、$table、$exists);
}
返回parent::newPivot($parent,$attributes,$table,$exists);
}
}
价目表型号:
类价格表扩展模型{
公共功能产品()
{
返回$this->belongtomany(“产品”);
}
公共函数newPivot(模型$parent,数组$attributes,$table,$exists)
{
if($Product的父实例)
{
返回新的ProductPricePivot($parent、$attributes、$table、$exists);
}
返回parent::newPivot($parent,$attributes,$table,$exists);
}
}
支点:
类ProductPricePivot扩展了Pivot{
公共功能产品()
{
返回$this->belongsTo(“产品”);
}
公共函数价格表()
{
返回$this->belongsTo('PriceList');
}
公共功能价格()
{
返回$this->hasMany('ProductPrice');
}
}
现在ProductPrice再次扩展了模型,只是一个标准模型,没有任何附加方法
这是正确的吗?如果是这样,那么按照上面的示例,如何将新的数量/价格级别添加到产品1010的价目表1中
目前,在建立关系时,我正在做:
$productID=1010;
$priceListID=1;
$priceList=priceList::find($priceListID);
$priceList->products()->attach($productID);
$productToPriceList=$priceList->products()->find($productID);
我在这里迷路了。。。我发现了这种关系,但我现在如何将下一个数量价格级别附加到它
有人能举一个例子,如何使用这种关系或链接到我可以找到更多关于它的页面吗?是的,我查了Laravel的文档,是的,我也用谷歌搜索了一下
谢谢大家! 如您所述,我在这里看到两种类型的关系:
价格表
和产品价格
(包含“最小数量”和“价格”)值之间的关系*====*============*===============*
| id | product_id | price_list_id |
*====*============*===============*
现在,模型:
产品:
class Product extends Eloquent {
protected $table = 'products';
public function price_lists()
{
return $this->belongsToMany('PriceList', 'products_to_pricelists', 'price_list_id');
}
}
价目表:
class PriceList extends Eloquent {
protected $table = 'price_lists';
public function prices()
{
return $this->hasMany('ProductPrice');
}
}
价格:
class ProductPrice extends Eloquent {
protected $table = 'product_prices';
}
现在很简单:
$productID = 1010;
$list_id = 1;
$theProduct = Product::find( $productID );
$theProductPriceLists = $theProduct->price_lists; // Don't use parens
$theList = Product::find( $productID )->price_lists()->where('price_lists.id', $list_id)->first(); // Here you use parens
$theListPrices = $theList->prices; // Again no parens
Laravel只需为您管理枢轴连接
希望能有所帮助嗨,谢谢你的主意!最后我做了:
$product=product::find($productID)$产品->价格表()->附加($priceListID)$prodToPriceList=$product->pricelists()->find($priceListID)$prodToPriceList->prices()->创建([…数量和价格数组…])代码>