Home > PHP Framework > ThinkPHP > body text

How to add data to Thinkphp5 model

angryTom
Release: 2020-03-18 09:39:12
forward
3159 people have browsed it

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());
    }
  }
 }
Copy after login

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!

Related labels:
source:www.100txy.com
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