gpt4 book ai didi

php - Laravel 5 更新返回旧关系

转载 作者:行者123 更新时间:2023-11-29 20:13:23 25 4
gpt4 key购买 nike

我有一个“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'])现在它明确仅使用 nameage参数。我知道它不干,因为你必须保留 $fillable->only 同步数组,但任何刚接触代码的人都可以从 Controller 知道发生了什么。

关于php - Laravel 5 更新返回旧关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39942075/

25 4 0
文章推荐: javascript将正则表达式的字符串转换为类型对象
文章推荐: javascript - Asp.Net Repeater - 通过 Javascript 调用 ItemCommand 事件
文章推荐: javascript - 随机淡化
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com