读一读

use Carbon\Carbon

用Carbon::方法等

now() today() tomorrow()

toDateTimeString()将时间转换为字符串

toDateString()



response($context,$state);//$context就是响应内容,$state响应状态
response()->json([..]);//响应json字符串
response()->download('文件路径','下载后文件名');
response()->cookie('name','value');//响应带上cookie
response()->view('resource/view下的模板文件');//响应视图

$user = DB::table('user')->paginate(10);
return view('view',[user=>$user]);

简单分页用simplePaginate

视图中{!! $user->render()!!} 显示下一页等工具栏


在AppServiceProvider的boot方法中添加

public function boot(){
    DB::listen(function($sql,$bindings,$time)){
        $sql就是sql语句,$bindings为参数,$time就是运行的时间
    }
}

这个用来调试就很好,直接监控所有的sql语句


第一种  毕包,发生错误自动回滚,成功自动提交,好用点

DB::transaction(function(){
DB::......事务操作等
});

第二种

DB::beginTransation();
if($somethingIsFailed){
    DB::rollback();
    return false;
}
DB::commit();

DB::insert('insert into user(id,name,email,password) values(?,?,?,?),[1,..,...,...])

同样的有select,update,delete

通用的statement,一般执行create,drop,grant等

insertGetId()插入获取id


dd()方法相当于print_r()方法,会直接中断下面程序


创建模型User

php artisan make:model User

记得引用User后再用

User::where("id",1)->get();

这个模型自动对应的是:配置前缀+users,注意会加s


protected $table="表名";//设置对应的表,最好指定一下好
protected $primarykey='id';//指定主键键名,默认id


更新和插入都会记录updated_at时间,这个字段默认存在

public $timestamps=false;//取消使用updated_at字段

数据库操作

DB::connection()->getPdo()
connection('game');//可以指定连接哪个数据库,game是在database.php配置文件的connections下配置的
DB::table('student')->where('id','>',2)->get();
table('table_name');//表示要对哪个表进行操作
chunk(每次处理的数据条数,function($data));//用于处理大堆数据,分批处理
pluck('字段')//获取单个字段的所有数据
first()//获取第一条记录
value('字段')//获取第一条记录的某个字段
聚合函数
count(),max(),min(),avg(),sum();//终结型方法,放在后面,除count外,传参数字段