php - Laravel 5 更新返回旧关系

标签 php mysql laravel eloquent

我有一个“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/

相关文章:

php - 将 mysql 时间戳转换为来自 Code igniter 的实际时间 mm dd yyyy hh mm

php - 在 PHP 脚本中获取 max_execution_time

java - 如何在基于角色的访问控制上实现默认角色

Laravel 分页不适用于数组而不是集合

php - 使用PHP在网页中显示尚未出现在数据库记录列表中的结果

php - 通过 PHP 从 mysql 获取数据,然后将具有相似列值和计数的行分组

java - 即使在数据库中插入元素,SqliteDatabse 也显示为空

带输入按钮的 Laravel Blade if 语句

laravel - 在 Eloquent 模型中使用时间字段

php - Zend框架2 : How much unit testing to do on controllers?