Thinkphp5模型

  • 实例化模型

    $data = User::get(1)->toArray();


    $model = model(“User”);


    $model = new User; $data = $model::get(1)->toArray();


    $model = \Think\Loader::model(“User”);

  • 闭包函数

    $data = User::get(function($query){ $query -> where(“id”,10); })->toArray();

  • 单条记录

    $data = User::where(“id”,10)->field(“username,password”)->find();

  • 多条记录

    //$models = User::all(“1,2,3”); $models = User::all(function($query){ $query->where(‘id’,’in’,[1,2,3])->field(“username,password”); });


    $models = User::where(‘id’,’>’,5)->field(“username,email”)->select();


    foreach($models as $model){ dump($model->toArray()); }

  • 单个字段

    $username = User::where(‘id’,10)->value(‘username’);

  • 列值

    $arr = User::column(“email”,”username”);//username = > email

  • 添加数据

    //post数据 $res = User::create([ “username”=>’damon’, “password”=>md5(‘pwd’), “email”=>’yank0362@qq.com’ ]);


    $res = User::create([ “username”=>’damon’, “password”=>md5(‘pwd’), “email”=>’yank0362@qq.com’ ],true);//过滤数据库中不存在的字段


    $res = User::create([ “username”=>’damon’, “password”=>md5(‘pwd’), “email”=>’yank0362@qq.com’ ],[‘username’,’email’]);//只更新配置的字段


    dump($res->id);//自增主键id dump($res);

    $userModel = new User; $userModel->username = ‘damon’; $userModel->password = ‘pwd’; $userModel->email=’yank0362@qq.com’; $res = $userModel->save();


    $userModel->allowField(true)->save([ “usename”=>”damon”, “password”=>”pwd”, “email”=>”email” ]);//过滤数据表中不存在字段


    $userModel->allowField([“username”])->save([ “usename”=>”damon”, “password”=>”pwd”, “email”=>”email” ]);//过滤数据表中不存在字段

    dump($userModel->id); //使用saveAll(二维数组),插入多条记录

  • 更新数据

    User::update([
    “id”=>1,
    “name”=>”damon”,
    “email”=>”yank0362@qq.com”
    ]);//根据传入的主键ID自动更新数据,无法知道影响行数,不常用,可以有第2参数,第2参数可以是闭包函数

    $res = User::where(“id”,”<“,5)->update([“username”=>”damon”,”email”=>”aa@q.com”]);
    //返回更新影响行数

    $userModel = User::get(1);
    $userModel->username=”damon”;
    $userModel->email=”aa@qq.com”;
    $res = $userModel->save();//返回影响行数

    $userModel = new User;
    $userModel->save([“email”=>”yank0362@qq.com”],[“id”=>5]);

  • 删除数据

    User::destroy(1);
    User::destroy([“id”=>2]);
    User::destroy(function($query){
    $query->where(“id”,”<“,5);
    });

    $userModel=User::get(5);
    $userModel->delete();

0

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据