2016-09-14 61 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