Home > PHP Framework > ThinkPHP > body text

How to call the model in thinkphp5

藏色散人
Release: 2019-11-09 09:37:28
Original
4283 people have browsed it

How to call the model in thinkphp5

thinkphp5 method of calling model

ThinkPHP5.0 model calling

1. Model classes can be called statically or instantiated, for example:

Recommended learning: thinkphp5

// 静态调用
$user = User::get(1);
$user->name = 'thinkphp';
$user->save();
// 实例化模型
$user = new User;
$user->name= 'thinkphp';
$user->save();
// 使用 Loader 类实例化(单例)
$user = Loader::model('User');
// 或者使用助手函数`model`
$user = model('User');
$user->name= 'thinkphp';
$user->save();
Copy after login

2. Model initialization

1. The model also supports initialization. Different from the initialization of the controller, the initialization of the model is to override the initialize of the Model, as follows

namespace app\index\model;
use think\Model;
class Index extends Model
{
    //自定义初始化
    protected function initialize()
    {
        //需要调用`Model`的`initialize`方法
        parent::initialize();
        //TODO:自定义的初始化
    }
}
Copy after login

2. You can also use the static init method. It should be noted that init is only executed when it is instantiated for the first time, and you need to pay attention to the specifications of static calls in the method, as follows

namespace app\index\model;
use think\Model;
class Index extends Model
{
    //自定义初始化
    protected static function init()
    {
        //TODO:自定义的初始化
    }
}
Copy after login

The above is the detailed content of How to call the model in thinkphp5. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template