我最近开始使用Laravel4 . 在多个关系的情况下,我在更新数据透视表数据时遇到一些问题 .
情况是:我有两个表: Product , ProductType . 它们之间的关系是 Many to many . 我的模特是
class Product extends Eloquent {
protected $table = 'products';
protected $primaryKey = 'prd_id';
public function tags() {
return $this->belongsToMany('Tag', 'prd_tags', 'prta_prd_id', 'prta_tag_id');
}
}
class Tag extends Eloquent {
protected $table = 'tags';
protected $primaryKey = 'tag_id';
public function products()
{
return $this->belongsToMany('Product', 'prd_tags', 'prta_prd_id', 'prta_tag_id');
}
}
在将数据插入数据透视表prd_tags时,我做了:
$product->tags()->attach($tag->tagID);
但是现在我想更新此数据透视表中的数据,将数据更新到数据透视表的最佳方法是什么 . 比方说,我想删除一些标签并为特定产品添加新标签 .
4 回答
旧问题,但是在2013年11月13日,updateExistingPivot方法被公开用于多对多关系 . 这还没有在官方文档中 .
截至2014年2月21日,您必须包含所有三个参数 .
在您的情况下,(如果您想更新数据透视字段'foo'),您可以:
或者,如果要触摸父时间戳,可以将最后一个布尔值false更改为true .
拉请求:
https://github.com/laravel/framework/pull/2711/files
我知道这是一个老问题,但如果你仍然对解决方案感兴趣,那么它是:
假设您的数据透视表有'foo'和'bar'作为附加属性,您可以这样做以将数据插入该表:
使用laravel 5.0时的另一种方法
这是完整的例子: