Three ways of Laravel database operation

Laravel provides 3 ways to manipulate the database: the DB facade (the original way), the query builder and the Eloquent ORM.

1. DB facade of database operation

1. Query operation

//返回一个二维数组
DB::select("select * from table");  

2. New operation

//新增成功则返回true
DB::insert("insert into table(vip_ID,vip_name,vip_type,vip_fenshu) values(?,?,?,?)",[5,'小明','出行',670]);

3. Update operation

//更新成功返回true
DB::update('update vipinfo set vip_fenshu= ? where vip_ID= ? ',[700,5]);

4. Delete operation

// 返回的是删除的行数。
DB::delete('delete from vipinfo where vip_ID= ?',[5]); 

2. Query builder for database operations

1. Use the query builder to implement addition, deletion, modification and query

(1) New
$bool=DB::table("vipinfo")->insert(['vip_ID'=>6,'vip_name'=>'zls','vip_type'=>"出行",'vip_fenshu'=>800]);  
echo $bool;  //返回bool值  
 //如果想得到新增的id,则使用insertGetId方法  
  $id=DB::table("vipinfo")->insertGetId(['vip_ID'=>5,'vip_name'=>'wyp','vip_type'=>"出行",'vip_fenshu'=>800]);  
  echo $id;  
 //插入多条数据  
 $bool=DB::table("vipinfo")->insert([  
        ['vip_ID'=>5,'vip_name'=>'wyp','vip_type'=>"出行",'vip_fenshu'=>800],  
        ['vip_ID'=>6,'vip_name'=>'zls','vip_type'=>"出行",'vip_fenshu'=>800],  
]);  
echo $bool;  //返回bool值  
(2) Modification
$bool=DB::table("vipinfo")->where('vip_ID',6)->update(['vip_fenshu'=>500]);  
echo $bool;  
//自增  
$bool=DB::table("vipinfo")->where('vip_ID',6)->increment("vip_fenshu");//自增1  
$bool=DB::table("vipinfo")->where('vip_ID',6)->increment("vip_fenshu",3);//自增3  
echo $bool;  
//自减  
$bool=DB::table("vipinfo")->where('vip_ID',6)->decrement("vip_fenshu");//1  
$bool=DB::table("vipinfo")->where('vip_ID',6)->decrement("vip_fenshu",3);//自增3  
echo $bool;  
//自增时再修改其他字段  
$bool=DB::table("vipinfo")->where('vip_ID',6)->increment("vip_fenshu",3,['vip_name'=>'dbdibi']);//自增3  
(3) delete
$num=DB::table("vipinfo")->where('vip_ID',6)->delete();//删除1条  
$num=DB::table("vipinfo")->where('vip_ID','>',4)->delete();//删除多条  
echo $num;  //删除的行数  
$num=DB::table("vipinfo")->truncate();//删除整表,不能恢复,谨慎使用  
(4) Inquiry
//get()返回多条数据  
$student=DB::table("vipinfo")->get();  
 var_dump($student);    
//first()返回1条数据  
$student=DB::table("vipinfo")->first();  //结果集第一条记录  
$student=DB::table("vipinfo")->orderBy('vip_ID','desc')->first();//按vip_ID倒序排序  
var_dump($student);    
//where()条件查询  
$student=DB::table("vipinfo")->where('vip_ID','>=',2)->get(); //一个条件     
$student=DB::table("vipinfo")->whereRaw('vip_ID> ? and vip_fenshu >= ?',[2,300])->get(); //多个条件  
dd($student);  
//pluck()指定字段,后面不加get  
$student=DB::table("vipinfo")->pluck('vip_name');  
dd($student);  
//lists()指定字段,可以指定某个字段作为下标  
$student=DB::table("vipinfo")->lists('vip_name','vip_ID');   //指定vip_ID为下标  
dd($student);  
$student=DB::table("vipinfo")->lists('vip_name');   //不指定下标,默认下标从0开始  
//select()指定某个字段  
$student=DB::table("vipinfo")->select('vip_name','vip_ID')->get();  
dd($student);  
//chunk()每次查n条  
$student=DB::table("vipinfo")->chunk(2,function($students){  //每次查2
    var_dump($students);  
    if(.......) return false;  //在满足某个条件下使用return就不会再往下查了  
});  

2. Use aggregate functions

//count()统计记录条数  
$nums=DB::table("vipinfo")->count();  
echo $nums;  
//max()某个字段的最大值,同理min是最小值  
$max=DB::table("vipinfo")->max("vip_fenshu");  
echo $max;  
//avg()某个字段的平均值  
$avg=DB::table("vipinfo")->avg("vip_fenshu");  
echo $avg;  
//sum()某个字段的和  
$sum=DB::table("vipinfo")->sum("vip_fenshu");  
echo $sum;  

3. Database Operation - Eloquent ORM

1. Introduction, model establishment and query data

Introduction: The Eloquent ORM that comes with laravel is an ActiveRecord implementation for database operations. Each data table has a corresponding model for data table interaction.

To build a model, create a Student model in the app directory, that is, Student.php, without any suffix.

<?php  
namespace App;  
use Illuminate\Database\Eloquent\Model;  
class Student extends Model{  
    //指定表名  
protected $table= 'vipinfo';  
//指定主键  
protected $primaryKey= 'vip_ID';  
}  

Add a test3 method to the Student controller to configure routingRoute::get('test3',['uses'=>'StudentController@test3']);

public function test3(){  
    // all()方法查询所有数据  
    $studnets=Student::all();  
    dd($studnets);  

    //find()查询一条,依据主键查询。findOrFail()查找不存在的记录时会抛出异常  
    $student=Student::find(5);  //主键为5的记录  
    var_dump($student['attributes']);  

    //查询构造器的使用,省略了指定表名  
    $student=Student::get();    
    var_dump($student);  
}  

2. New data, custom timestamp, batch assignment

(1) Use the save method to add

Laravel will maintain the created_at and updated_at fields by default. These two fields store timestamps and are 11-bit integers. Therefore, these two fields need to be added to the database when using them. If you don't need this feature, just add an attribute to the model: public $timestamps=false;and a method to save the current timestamp to the database

protected function getDateFormat(){  
    return time();  
}  

This eliminates the need for those two fields.

In the controller write:

$student=new Student();  
//设定数据  
$student->vip_name='xiaoming';  
$student->vip_type='出行';  
$student->vip_fenshu=900;  
$bool=$student->save();  //保存  
echo $bool;  

When the timestamp of a record is obtained from the database, the timestamp formatted by date is obtained by default. If you want to obtain the original timestamp, the asDateTime method is added to the model.

protected function asDateTime($val){  
   return $val;  
} 

(2) When using the create method to add, you need to add in the model:

protected $fillable=['vip_name','vip_fenshu','vip_type'];   //允许批量赋值的字段  

In the controller write:

Student::create(['vip_name'=>'mmm','vip_fenshu'=>999,'vip_type'=>'出行']);  

This will add success!

3) firstOrCreate() finds records by attributes, if not, add them

$student=Student::firstOrCreate(['vip_name'=>'mmm']);  
echo $student;  

(4) firstOrNew() finds records by attributes, if not, a new instance will be created. If you need to save, call the save method() yourself

$student=Student::firstOrNew(['vip_name'=>'mmm']);  
$student->save();  
echo $student;  

change the data

//通过模型更新数据  
$student=Student::find(2);  
$student->vip_fenshu=10000;  
$student->save(); //返回bool值  
//通过查询构造器更新  
$num=Student::where('vip_ID','>',2)->update(['vip_fenshu'=>2000]);  
echo $num;  //返回更新的行数  

delete data

//(1)通过模型删除数据  
$student=Student::find(11);  
$student->delete(); //返回bool值  
//(2)通过主键删除  
 $num=Student::destroy(10); //删除主键为10的一条记录  
 echo $num; //返回删除的行数  
 $num=Student::destroy(10,5); //删除多条  或者$num=Student::destroy([10,5]);  
 echo $num; //返回删除的行数  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325645437&siteId=291194637
Recommended