码迷,mamicode.com
首页 > 数据库 > 详细

学习新框架laravel 5.6 (第二天)-DB,控制器及模型使用

时间:2018-08-01 11:56:19      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:begin   comm   bsp   connect   截断   database   fun   incr   数据库事务   

DB类使用,控制器使用及模型使用

链接数据库:

  /config/database.php

       /.env 

  

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

 控制器中查询Mysql数据

use Illuminate\Support\Facades\DB;
//获取数据
        $data = DB::table(‘test‘)->where( array(‘id‘ => 1) )->get();     //tp中select();
        dump($data);

        $data = DB::table(‘test‘)->where( array(‘id‘ => 1) )->first();   //tp中 find()
        dump($data);

        $data = DB::table(‘test‘)->where( array(‘id‘ => 1) )->pluck(‘name‘);   //tp中 column()
        dump($data);

        $data = DB::table(‘test‘)->where( array(‘id‘ => 1) )->select(‘id‘,‘name‘)->get();   //tp中 field()
        dump($data);


        // // 插入 
        $data = DB::table(‘test‘)->insert( [‘name‘ => ‘john@example.com‘, ‘sex‘ => 0]);  //返回bool   //tp中 add()
        dump($data);

        $id = DB::table(‘test‘)->insertGetId([‘name‘ => ‘john@example.com‘, ‘sex‘ => 0]);//返回id    
        dump($id);


        // 更新
        $data = DB::table(‘test‘)
          ->where(‘id‘, 1)
          ->update([‘sex‘ => 0]);   //返回更新条数  //tp中 save()
        dump($data);

        DB::table(‘test‘)->where([‘id‘=> 1])->increment(‘num‘, 5);  //自增    //tp中 setInc()
        DB::table(‘test‘)->where([‘id‘=> 2])->decrement(‘num‘, 5);            //tp中 setDec()

        //删除
        DB::table(‘test‘)->where( [‘id‘=> 1] )->delete();

        DB::table(‘test‘)->truncate();  //截断表 ,清空表内容,自增恢复到初始值1

        // 数据库事务处理
        DB::transaction(function(){
            $id = DB::table(‘test‘)->insertGetId([‘name‘ => ‘john@example.com‘, ‘sex‘ => 0]);//返回id
            DB::table(‘test‘)->where([‘id‘=> $id])->increment(‘num‘, 5);  //自增
        });
        DB::beginTransaction();
        DB::rollBack();
        DB::commit();

 

学习新框架laravel 5.6 (第二天)-DB,控制器及模型使用

标签:begin   comm   bsp   connect   截断   database   fun   incr   数据库事务   

原文地址:https://www.cnblogs.com/inkwhite/p/9399516.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!