Home  >  Article  >  PHP Framework  >  How to add data to Thinkphp5 model

How to add data to Thinkphp5 model

angryTom
angryTomforward
2020-03-18 09:39:123177browse

This article introduces two methods for adding data to models in thinkphp5. I hope it will be helpful to friends who are learning thinkphp!

How to add data to Thinkphp5 model

Thinkphp5 model method of adding data

ThinPHP5 model has two methods of adding data, one is create, one is the save method, see the actual case code below.

<?php
namespace app\index\controller;
use think\Controller;
use app\index\model\User;
public function index(){
    //create方法添加数据
    $res=User::create([
      &#39;name&#39;=>&#39;lei&#39;,
      &#39;email&#39;=>&#39;leixiaotian@163.com&#39;,
      &#39;password&#39;=>&#39;123&#39;
    ],true);//true排除掉表中不存在的字段
    dump($res->id);
    dump($res);
    //save方法添加
    $userModel=new User;
    $userModel->name=&#39;lei&#39;;
    $userModel->email=&#39;leixiaotian@163.com&#39;;
    $userModel->save();
    dump($userModel->id);
    //sava数组方法
    $res=$userModel->save([
      &#39;name&#39;=>&#39;lei&#39;,
      &#39;email&#39;=>&#39;leixioatian@163.com&#39;
    ]);
    dump($res);
    //sava允许字段方法
    $userModel=new User;
    $res=$userModel
    ->allowField([&#39;name&#39;])
    ->save([
      &#39;name&#39;=>&#39;lei&#39;,
      &#39;email&#39;=>&#39;leixioatian@163.com&#39;
    ]);
    dump($res);
    //sava保存多条数据
    $userModel=new User;
    $res=$userModel->saveAll([
      [&#39;name&#39;=>&#39;lei&#39;],
      [&#39;name&#39;=>&#39;lei&#39;]
    ]);
    foreach ($res as $val) {
      dump($val->toArray());
    }
  }
 }

Recommended learning: thinkphp tutorial

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

Statement:
This article is reproduced at:www.100txy.com. If there is any infringement, please contact admin@php.cn delete