PHP笔记-laravel框架中Eloquent ORM实现增删改查

x33g5p2x  于2022-05-16 转载在 其他  
字(3.2k)|赞(0)|评价(0)|浏览(313)

表结构是这样的:

/*
SQLyog Ultimate v12.09 (64 bit)
MySQL - 5.7.12 : Database - laravel
*********************************************************************
*/

/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`laravel` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci */;

USE `laravel`;

/*Table structure for table `student` */

DROP TABLE IF EXISTS `student`;

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(64) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

/*Data for the table `student` */

insert  into `student`(`id`,`name`,`age`) values (2,'小张',19),(3,'小明',18),(4,'小张',19);

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

源码如下:

路由web.php添加:

Route::prefix('student')->group(function(){

    ......
    ......
    Route::get('ormInsert', 'StudentController@ormInsert');
    Route::get('ormDelete', 'StudentController@ormDelete');
    Route::get('ormModify', 'StudentController@ormModify');
    Route::get('ormSelect', 'StudentController@ormSelect');
});

这个config/database.php是数据库相关的设置,目前不用改,对应mysql是这样的

需要修改的是

.env

修改为如下:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=root

新建Student.php

代码如下:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Student extends Model {

    // 指定表名
    protected $table = 'student';

    // 指定ID
    protected $primaryKey = 'id';

    // 自动维护时间戳
    public $timestamps = true;

    // 指定允许批量赋值的字段
    protected $fillable = ['name', 'age'];

    // 指定不允许批量赋值的字段
    protected $guarded = [];

//    protected function getDateFormat(){
//
//        return time();
//    }
//
//    protected function asDateTime($val){
//
//        return $val;
//    }

}

新建StudentController.php

<?php

namespace App\Http\Controllers;

use App\Student;
use Illuminate\Support\Facades\DB;

class StudentController extends Controller{

   	......
    ......
    ......

    public function ormInsert(){

        $student = new Student();
        $student->name = '小红';
        $student->age = 19;
        $bool = $student->save();
//        dd($bool);

        $student = Student::create(
          ['name' => '小张', 'age' => 20]
        );
//        dd($student);

        //firstOrCreate()
        $student = Student::firstOrCreate(
            ['name' => '小王', 'age' => 32]
        );

//        dd($student);

        //firstOrNew这个需要手动保存
        $student = Student::firstOrNew(
            ['name' => '小黑', 'age' => 33]
        );

        $bool = $student->save();
        dd($bool);

        return "ormInsert";
    }

    public function ormDelete(){

        // 通过模型删除
        $student = Student::find(1);
        $bool = $student->delete();
        var_dump($bool);

        // 通过主键删除
        $num = Student::destroy(2);
        var_dump($num);
        $num = Student::destroy([2, 3]);
        var_dump($num);

        // 条件删除
        $num = Student::where('id', '>', 10)->delete();
        var_dump($num);

        return "ormDelete";
    }

    public function ormModify(){

        $student = Student::find(1);
        $student->name = 'kitty';
        $bool = $student->save();
        var_dump($bool);

        $num = Student::where('id', '>', 5)->update(
          ['age' => 38]
        );
        var_dump($num);
        return "ormModify";
    }

    public function ormSelect(){

        $student = Student::find(1);
        dd($student);
        return "ormSelect";
    }

}

相关文章