【问题标题】:Laravel 5.2 is not update parent's timestamp after updating childLaravel 5.2 更新子代后不更新父代时间戳
【发布时间】:2016-07-16 04:01:49
【问题描述】:

在 Laravel 框架中,我有 2 个模型。首先是问题模型:

class Question extends Model
{
     protected $table = 'questions';
     protected $fillable = [...];
     public function answers()
     {
         return $this->hasMany('App\Models\Answer');
     }
     ...
}

和答案模型:

class Answer extends Model
{
     protected $table = 'answers';
     protected $fillable = [...];
     protected $touches = ['question'];
     public function question()
     {
         return $this->belongsTo('App\Models\Question');
     }
     ...
}

我用代码更新了答案模型中的一些属性:

$answer = $answer->select('id')
            ->where('id', $id)
            ->firstOrFail();
$answer->update($data);

当我检查数据库时,Answers 表中的数据会更新,包括 updated_at 列。但是,它的父级(问题表)不会更新 updated_at 列中的时间戳。

如何解决这个问题?谢谢。

【问题讨论】:

  • 只是一些快速的健全性检查:您的answers 表是否有question_id 字段(验证关系设置是否正确)?您的 answers 表是否有 question 字段(以验证字段名称与关系属性不冲突)?
  • 我的答案表有 question_id 作为外键,没有问题字段。
  • answers 表是否有touches 字段?手动调用$answer->question()->touch()可以吗?
  • 不,答案表没有触摸字段。调用 $answer->question()->touch() 不起作用。但是,如果我调用 $question = Question::find($questionId); $问题->触摸(); ,它有效。
  • 听起来这种关系不起作用。 dd($answer->question) 显示什么? idquestions 表的主键吗?

标签: laravel eloquent touches


【解决方案1】:

只需按照基础做如下操作:

Question::find($questionId)->touch();

这将更新您想要执行的 timestatmp。

【讨论】:

  • 如果我有很多需要更新的函数或者我有很多嵌套关系,这种方式会更加复杂。
猜你喜欢
  • 1970-01-01
  • 2017-06-06
  • 1970-01-01
  • 1970-01-01
  • 2013-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多