我有一个“belongsTo”关系。
public function relation()
{
return $this->belongsTo('App\Relation', 'relation_id');
}
当我创建一个实例时,一切都按预期工作。返回包含关系的新实例。
public function store(Request $request)
{
$instance = $this->model->create($request->all());
return $instance;
}
当我更新“relation_id”时,它会返回旧关系。它不会立即返回。
public function findOrFail($id)
{
$link = $this->model
->with('relation')
->findOrFail($id);
return $link;
}
public function update(Request $request, $id)
{
$instance = $this->findOrFail($id);
$instance->update($request->all());
//$instance = $instance ->fresh();
return $instance ;
}
似乎使用 $instance->fresh() 或删除 ->with('relation') 新关系会立即在当前实例中返回。
我想知道为什么它不像create那样立即返回新关系。
最佳答案
create()
函数返回实例请参阅 API DOC on create()
update()
返回bool
请参阅API DOC on update()
更新后,您需要使用 load() 重新加载关系或fresh()正如你所说。
<小时/>You only update current model / table not any relationships bound to it.
很可能您丢失了(或不正确)$fillable
模型中的数组。这可以保护您免受“批量分配”漏洞的影响。
阅读文档中有关主题的更多信息 here .
罢工><小时/>
A mass-assignment vulnerability occurs when a user passes an unexpected HTTP parameter through a request, and that parameter changes a column in your database you did not expect. For example, a malicious user might send an is_admin parameter through an HTTP request, which is then passed into your model's create method, allowing the user to escalate themselves to an administrator.
提示:
请勿使用$request->all()
,而是使用 $request->only(['name', 'age'])
现在它明确仅使用 name
和age
参数。我知道它不干,因为你必须保留 $fillable
与 ->only
同步数组,但任何刚接触代码的人都可以从 Controller 知道发生了什么。
关于php - Laravel 5 更新返回旧关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39942075/