【发布时间】: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)显示什么?id是questions表的主键吗?