更新数据透视表,以备多对多关系laravel4

问题描述:

我最近开始使用Laravel4。在更新数据透视表时,我遇到了一些问题,以防万一。更新数据透视表,以备多对多关系laravel4

的情况是: 我有两个表:产品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'); 
    } 
} 

在插入数据透视表prd_tags,我所做的:

$product->tags()->attach($tag->tagID); 

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

+0

你看过的信息文档?它是否有帮助... http://four.laravel.com/docs/eloquent#working-with-pivot-tables – 2013-04-11 12:24:01

+0

@PhillSparks:是的,我已经阅读了这份文件。有一种叫做sync的方法来做到这一点,它将分别采用id的数组和插入和删除,但是如果我的数据透视表的属性不是两个表的id,那该怎么办?同步方法应该采用一组对象而不是整数数组。 – Sameer 2013-04-15 07:55:58

+1

Eloquent提倡简单的表设计,其中数据透视表具有用于引用行的ID列。雄辩不是为迎合其他数据库设计而设计的,因为有更全面的ORM解决方案。 – 2013-04-15 08:36:17

我知道这是一个老问题,但如果你还有兴趣的解决方案,那就是:

比方说您的数据透视表有“富”和“酒吧”作为附加属性,你可以这样做将数据插入到该表:

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

老问题,但11月13,2013年,updateExistingPivot方法被公开为多对多的关系。这还没有在官方文档中。

public void updateExistingPivot(mixed $id, array $attributes, bool $touch) 

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

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

在你的情况下,(如果你想更新枢轴场“富”),你可以这样做:

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

或者,如果你要摸父戳你可以改变过去的布尔值false为true 。

拉请求:

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

+2

太棒了。我希望官方文档已经更新,以突出这种方法。这应该被标记为正确答案。干杯! – 2014-04-01 01:07:09

+0

完美,谢谢! – Guicara 2014-08-18 09:54:45

+0

'public void',错字? – haakym 2015-11-19 10:12:38

为此而与laravel工作的另一种方法5.0+

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

我必须做'$ pivot-> pivot-> save();'保存我的数据透视表。 – MECU 2016-04-22 22:19:44

+0

这实际上是我认为最简单的解决方案。 – dexterb 2017-05-22 17:15:19

+0

如果你使用这个方法,你会得到一个错误:'间接修改重载属性没有效果' – JackalopeZero 2017-11-10 14:16:24

这是完整的例子:

$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);