在多个关系laravel4的情况下更新数据透视表

Sam*_*eer 8 many-to-many pivot-table laravel eloquent laravel-4

我最近开始使用Laravel4.在多个关系的情况下,我在更新数据透视表数据时遇到一些问题.

情况是:我有两个表:Product,ProductType.它们之间的关系是多对多的.我的模特是

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

在将数据插入数据透视表prd_tags时,我做了:

$product->tags()->attach($tag->tagID);
Run Code Online (Sandbox Code Playgroud)

但是现在我想更新此数据透视表中的数据,将数据更新到数据透视表的最佳方法是什么.比方说,我想删除一些标签并为特定产品添加新标签.

And*_*rew 33

旧问题,但是在2013年11月13日,updateExistingPivot方法被公开用于多对多关系.这还没有在官方文档中.

public void updateExistingPivot(mixed $id, array $attributes, bool $touch)
Run Code Online (Sandbox Code Playgroud)

- 更新表上的现有数据透视记录.

截至2014年2月21日,您必须包含所有三个参数.

在您的情况下,(如果您想更新数据透视字段'foo'),您可以:

$product->tags()->updateExistingPivot($tag->tagID, array('foo' => 'value'), false);
Run Code Online (Sandbox Code Playgroud)

或者,如果要触摸父时间戳,可以将最后一个布尔值false更改为true.

拉请求:

https://github.com/laravel/framework/pull/2711/files

  • 太棒了.我希望更新官方文档以突出显示此方法.这应该标记为正确的答案.干杯! (2认同)

Gok*_*oks 6

使用laravel 5.0+时的另一种方法

$tag = $product->tags()->find($tag_id);
$tag->pivot->foo = "some value";
$tag->pivot->save();
Run Code Online (Sandbox Code Playgroud)


Shi*_*hir 5

我知道这是一个老问题,但如果你仍然对解决方案感兴趣,那么它是:

假设您的数据透视表有'foo'和'bar'作为附加属性,您可以这样做以将数据插入该表:

$product->tags()->attach($tag->tagID, array('foo' => 'some_value', 'bar'=>'some_other_value'));
Run Code Online (Sandbox Code Playgroud)