DB facade实现CURD

数据表

CREATE TABLE IF NOT EXISTS students(
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `name` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '姓名',
    `age` TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '年龄',
    `sex` TINYINT UNSIGNED NOT NULL DEFAULT 10 COMMENT '性别',
    `created_at` INT NOT NULL DEFAULT 0 COMMENT '新增时间',
    `updated_at` INT NOT NULL DEFAULT 0 COMMENT '修改时间'
)ENGINE=InnoDB DEFAULT CHARSET=UTF8 AUTO_INCREMENT=1001 COMMENT='学生表';

在对应的控制器中的操作代码

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
class StudentController extends Controller
{
    //新增
    public function insert(){
        //返回一个布尔值
        $bool = DB::insert('insert into students(name,age) values (?,?)',
            ['bigz',18]
        );
        var_dump($bool);
    }
    //删除
    public function delete(){
        //返回修改的行数
        $num = DB::delete('delete from students where name = ?',
            ['bigz']);
        var_dump($num);
    }
    //更改
    public function update(){
        //返回修改的行数
        $num = DB::update('update students set age = ? where name = ?',
            [20,'bigz']);
        var_dump($num);
    }
    //查询
    public function select(){
        //返回一个数组
        $students = DB::select('select * from students');
        $student = DB::select('select * from students where name = ?',
            ['bigz']);
        dd($students);
        dd($student);
    }
}
posted @ 2017-04-02 23:27  郑闯  阅读(671)  评论(0编辑  收藏  举报