2013-03-25 116 views
7

我最近開始使用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

回答

5

我知道這是一個老問題,但如果你還有興趣的解決方案,那就是:

比方說您的數據透視表有「富」和「酒吧」作爲附加屬性,你可以這樣做將數據插入到該表:

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

老問題,但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

4

爲此而與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

0

這是完整的例子:

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