laravel数据库操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41179401/article/details/84959658

                                                laravel数据库操作

连接数据库:在.env文件里配置

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=12345678

1 使用DB facade原生实现CURD:

新建控制器StudentController.php:

<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
class StudentController extends Controller{
	public function index(){
		// 查询数据 返回值是一个数组
		$student = DB::select('SELECT username  FROM user WHERE id = ?',[1]);
		// 插入一条数据 返回影响行数
		 $insertNum = DB::insert('INSERT INTO user (username,password)VALUES(?,?)',["张三",sha1("123456")]);
		// 修改一条数据 返回影响行数
		 $updateNum = DB::update("UPDATE user SET username = ? WHERE id = ?",['李四',1]);
		// 删除一条数据 返回影响行数
		$deleteNum = DB::delete("DELETE FROM user WHERE id > ?",[3]);
	}
}

在routes.php里绑定路由到控制器/方法(StudentController/index);

routes.php:

Route::get('student',['uses'=>'StudentController@index']);

2 使用查询构造器实现CURD

之前的路由不变

StudentController.php:

public function index(){
		// 插入一条数据 返回值是bool值
		DB::table('user')->insert(['username'=>'张三','password'=>sha1('123456')]);
		// 插入多条数据 返回值是bool
		DB::table('user')->insert([
			['username'=>'张三','password'=>sha1('123456')],
			['username'=>'李四','password'=>sha1('123456')]
		]);
		// 插入一条数据并返回自增id
		DB::table('user')->insertGetId(['username'=>'张三','password'=>sha1('123456')]);
        
        // 更新 返回影响行数
		DB::table('user')->where('id',1)->update(['username'=>'张三']);
		// 更新 字段自增返回值是影响行数 如果不传第二个参数 默认自增1
		DB::table('user')->where('id',1)->increment('age',2);
		// 更新 字段自减 返回值是影响行数 同上
		DB::table('user')->where('id',1)->decrement('age',1);
        // 也可以在自增自减的同时更新其他数据
		DB::table('user')->where('id',1)->decrement('age',1,['username'=>'李四']);
        // 删除数据 返回影响行数
		DB::table('user')->where('id','>',16)->delete();
		DB::table('user')->truncate();  //清空数据表,无返回值
        //查询
        // get():查询所有字段数据
		// first():查询第一条
		// where():指定取出的条件
		// pluck():查询指定的字段
		// lists():查询指定的某个字段 并使用某个字段作为键
		// select():查询指定的某些字段
		// chunk():指定每次查询的个数
        dump(DB::table('user')->get());    //查询所有
		dump(DB::table('user')->first()); //从结果集中取出第一条
		dump(DB::table('user')->where('id','=',1)->get()); 
		dump(DB::table('user')->whereRaw('id = ? and username = ?',[1,'张三'])->get());                 
        //指定取出的条件
		dump(DB::table('user')->pluck('username')); //查询指定的字段
		dump(DB::table('user')->lists('username','id')); //查询指定的字段 并使用某个字段作为键
		dump(DB::table('user')->select('id','username')->get());
		 //指定查找某些字段
		DB::table('user')->chunk(2,function($student){
			dump($student);  //每次查询两条知道查询结束
		});
        //聚合函数
        $max = DB::table('user')->max('age');
		$min = DB::table('user')->min('age');
		$avg = DB::table('user')->avg('age');
		$sum = DB::table('user')->sum('age');
		$count = DB::table('user')->count();
		
	}

3 Eloquent ORM 操作数据库

使用模型:student.php:

<?php
namespace App;
use Illuminate\database\Eloquent\Model;
class Student extends Model{
	// 如果不指定表明 则表名默认和模型名的复数一致
	protected $table = 'student';  //指定表名
	protected $primaryKey = 'id';  //指定主键
}

 控制器StudentController.php:

查询数据:

<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Student;  //引入student模型
class StudentController extends Controller{
    public function index(){
		//查询数据
		dump(Student::all());  //查询表的所有记录	
		dump(Student::find(1)); //查询指定主键的记录
		// dump(Student::findOrFail(33));//查询指定主键的记录 没有会报错
        //还可以使用查询构造器里的方法
		dump(Student::get());//查询表的所有记录

        
	}
}

新增数据:

<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;

use App\Student;
class StudentController extends Controller{
public function index(){
        // 使用模型 新增数据
		$student = new Student();
		$student->username = '李四';
		$student->password = sha1('123456');
		$student->age = 21;
		$student->save();  //保存数据
        // 使用create方法创建数据 指定允许批量添加的数据字段
		Student::create(
		    ['username'=>'小明','password'=>sha1('123456'),'age'=>22]
		 );
        // firstOrCreate 查询指定用户 不存在则创建
		// dump(Student::firstOrCreate(['username'=>'小明']));
		// firstOrNew 查询指定用户 不存在则手动创建
		$student = Student::firstOrNew(
			['username'=>'小']
		);
		$student->save(); //手动保存 //返回值是bool值
    }
}

PS:使用save方法保存时会提示没有create_at和update_at两个字段,这两个是数据创建时间和修改时间,自动修改,如果不想用可以在模型里修改:

Student.php:

//指定数据添加时间和修改时间 必须是creat_at和update_at
	public $timestamps = true; //改为false就是不使用  
      // 指定数据创建修改的时间戳
  	protected function getDateFormat(){
  		return time();
  	}
  	// 获取时间数据时转化为时间戳
	protected function asDateTime($val){
	  	return $val;
	} 

PS:使用create方法新增数据是需要在模型里指定哪些字段可以批量添加

Student.php:

	//指定允许批量添加的数据字段
	protected $fillable = ['username','password','age'];  

修改数据:

//第一种 通过模型更新//返回值是bool值
$student = Student::find(1);
$student->username = 'admin';
$student->save();  
//第二种 通过查询语句批量更新 返回值是影响行数
Student::where('id','=',1)->update(
		['username'=>'张三']
);

删除数据:

// 删除
// 1 通过模型删除 返回值是一个bool值
$student = Student::find(6);
$student->delete();
// 2 通过主键删除 返回值是影响行数
Student::destroy(4,5);
// 3 通过条件删除 返回值是影响行数
Student::where('id','>',7)->delete();

猜你喜欢

转载自blog.csdn.net/qq_41179401/article/details/84959658