2016-09-14 60 views
1

我使用laravel,並且我在產品和訂單之間有多對多的關係。有一個稱爲訂單產品的數據透視表,它具有不時更新的附加信息。我想在更新數據透視表中相應的行時更新訂單表中的'updated_at'feild,或者例如添加新產品。 這可能嗎?如何在更新數據透視表時更新模型的'updated_at'

一個產品和訂單之間的關係是belongsToMany()

編輯:這裏是一些代碼

class Order extends Model 
{ 
protected $table = 'order'; 
protected $dates = ['updated_at']; 

public function products() 
    { 
     return $this->belongsToMany(Product::class, 'order_product'); 
    } 
} 

的當我想通過調用 $命令 - >產品去除其產品() - >分離()

那麼,我把$倒是在laravel文檔提到的陣列,多數民衆贊成here

我已經嘗試將其添加到產品型號,但它不工作。

+1

檢查了這一點:https://laravel.com/docs/5.3/eloquent-relationships#touching-parent-timestamps – Neat

回答

1

您可以使用Touching Parent Timestamps,這裏是一個例子(來自laravel文檔)。

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Comment extends Model 
{ 
    /** 
    * All of the relationships to be touched. 
    * 
    * @var array 
    */ 
    protected $touches = ['post']; 

    /** 
    * Get the post that the comment belongs to. 
    */ 
    public function post() 
    { 
     return $this->belongsTo('App\Post'); 
    } 
} 
+0

我已經試過這一點,這是行不通的。我認爲這是因爲我正在更新數據透視表而不是其中一個模型。 – user3552551

+0

那麼你使用的belongsToMany() - > withPivot()的權利,這應該仍然工作,因爲它只是返回一個關係,它至少適用於我 – Neat

+0

我添加了保護$ touches = ['order'];到產品模型。也許我沒有把它放在正確的地方? – user3552551