首页 文章

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

提问于
浏览
7

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

情况是:我有两个表: ProductProductType . 它们之间的关系是 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 回答

  • 5

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

    public void updateExistingPivot(mixed $id, array $attributes, bool $touch)
    
    • 更新表上的现有数据透视记录 .

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

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

    $product->tags()->updateExistingPivot($tag->tagID, array('foo' => 'value'), false);
    

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

    拉请求:

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

  • 4

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

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

    $product->tags()->attach($tag->tagID, array('foo' => 'some_value', 'bar'=>'some_other_value'));
    
  • 0

    使用laravel 5.0时的另一种方法

    $tag = $product->tags()->find($tag_id);
    $tag->pivot->foo = "some value";
    $tag->pivot->save();
    
  • 32

    这是完整的例子:

    $user = $this->model->find($userId);
        $user->discounts()
            ->wherePivot('discount_id', $discountId)
            ->wherePivot('used_for_type', null)
            ->updateExistingPivot($discountId, [
                'used_for_id' => $usedForId,
                'used_for_type' => $usedForType,
                'used_date_time' => Carbon::now()->toDateString(),
            ], false);
    

相关问题