如何在Laravel中从数据库重新加载/刷新模型? [英] How to reload/refresh model from database in Laravel?

查看:1586
本文介绍了如何在Laravel中从数据库重新加载/刷新模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一些测试中,我创建了一个用户模型,并且运行了一些需要保存某些属性的方法.在Rails中,我通常会调用user.reload之类的东西,它将重新填充数据库中的属性.

In some of my tests, I have a user model I have created and I run some methods that need to save certain attributes. In rails, I would typically call something like user.reload which would repopulate the attributes from the database.

laravel中有没有办法做到这一点?我通读了api,找不到适用的方法: http://laravel.com /api/4.1/Illuminate/Database/Eloquent/Model.html 关于正确"方法的任何想法吗?

Is there a way in laravel to do that? I read through the api and couldn't find a method for it: http://laravel.com/api/4.1/Illuminate/Database/Eloquent/Model.html Any ideas on the "right" way to do this?

推荐答案

我也看不到它.看来您必须:

I can't see it either. Looks like you'll have to:

$model = $model->find($model->id);

您也可以自己创建一个:

You can also create one yourself:

public function reload()
{
    $instance = new static;

    $instance = $instance->newQuery()->find($this->{$this->primaryKey});

    $this->attributes = $instance->attributes;

    $this->original = $instance->original;
}

只是在这里对其进行了测试,它看起来仍然有效,但是不确定Eloquen是一个相当大的类.

Just tested it here and it looks it works, not sure how far this goes, though, Eloquen is a pretty big class.

这篇关于如何在Laravel中从数据库重新加载/刷新模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆