PHP 框架之Laravel 数据库操作 ,查询构造器简介, Eloquent ORM 简介

在.env 文件中 调好配置文件

前四个不推荐用,知道,了解就好

查询表

$students = DB::select('select * from student');

插入

$bool = DB::insert('insert into student(name, age) values ("sean", 18)'); // 此处我使用双引号

修改

$bool = DB::update('update student set  age = 20 where name = "sean"');

删除

$num = DB::delete('delete from student where id > 1001');

查询构造器简介:

Laravel查询构造器(query builder) 用来建立及执行数据库查找语法

使用PDO参数绑定,以保护应用程序免于SQL注入,因此传入的参数不需要额外转义特殊字符

添加

$bool = DB::table('student') -> insert (['name' => 'imooc', 'age' => 25]);

//多条插入
$bool = DB::table('student') -> insert ([
			['name' => 'sean', 'age' => 21],
			['name' => 'sen', 'age' => 29],
			['name' => 'boom', 'age' => 22]
		]);

修改

$bool = DB::table('student') -> where('id', 1001) -> update(['name' => 'imo']);

删除

$bool = DB::table('student') -> where('id', 1001) -> delete();

查询

$bool = DB::table('student') ->where('id', '>' ,1001) -> get();


//多个限制查询
$bool = DB::table('student') ->whereRaw('id >= ? and age > ?',  [1005, 23]) ->get();

$bool = DB::table('student') 
    ->whereRaw('id >= ? and age > ?',  [1005, 23]) 
    ->lists('name');

$bool = DB::table('student')
		->select('id', 'name')
		->get();

聚合函数

包含 count(),  min(),  max(),  avg()    用法和get()一样

Eloquent ORM 简介

每个数据表都有一个与之相对应的模型用于和数据表交互

模型书写

<?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 = [];

	public function getDateFormat(){
		return time();
	}
}
?>

查询方法

public function orm(){
        // 查找所有    
		$students = Student::all(); 
        $students = Student::get(); 

        // 查找指定
        $students = Student::find(1004);

        // 条件查找
        $students = Student::where('id', '>', 1005)
			->orderBy('age', 'desc')
			->get();
	}

新增数据模型

public function orm(){
    // 使用新增数据模型
	$student = new Student();
	$student->name = 'shu';
	$student->age = 30;
	$bool = $student->save();
	dd($bool);

        $student = Student::find(1011);
	echo date('Y-m-d H:i:s', $student->create_at);

    //使用模型的Create方法新增数据
	$student = Student::create(
		['name' => 'jack'], 'age' => 26);

    //使用模型修改数据
        $student = Student::find(1011);
	$student->name = 'kitty';
	$student->save();

        $num = Student::where('id', '>', 1008)
		->update(['age' => 22]);

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

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

猜你喜欢

转载自blog.csdn.net/error311/article/details/88044939