作为程序员一定要保持良好的睡眠,才能好编程

Laravel数据库操作 orm

发布时间:2016-07-26

https://cs.phphub.org/     速查表


http://laravel-china.org/docs/5.1#environment-configuration


t1.jpg


使用原生SQL查询


配置好数据库连接以后,就可以使用DB 门面来运行查询。DB门页面为每种查询提供了相应的方法:

select  update insert  delete 和 statement


 public function index(){
   $users = DB::select('select * from users where active = ?', [1]);
   return view('user.index', ['users' => $users]);
 }
 //传递给select方法的第一个参数是原生的SQL语句,
 //第二个参数需要绑定到查询的参数绑定,通常,
 //这些都是where字句约束中的值。参数绑定可以避免SQL注入攻击。
 //他返回的是一个php stdClass 因此需要使用std->aaa 指向来访问。
 
 //使用命名绑定:
 $results = DB::select('select * from users where id = :id', ['id' => 1]);
 
 //插入:
 DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
 
 
 
  //$db=DB::connection("newcimie")->getPdo();
        //$db=DB::connection("newcimie")->select("select * from web_articlenav");
        //$db=DB::connection("newcimie")->select("select * from web_articlenav where mshow=?",[1]);
        //$db=DB::connection("newcimie")->select("select * from web_articlenav where mshow=? and pid=?",[1,0]);
        //$db=DB::connection("newcimie")->select("select * from web_articlenav where mshow=:mshow and pid=:pid",["mshow"=>1,"pid"=>0]);
        $db=DB::connection("newcimie")->select("select * from web_articlenav where mshow=:mshow and pid=:pid",["pid"=>0,"mshow"=>1]);
        
        dd($db);
 
 
 
 //更新:返回影响的行数
 $affected = DB::update('update users set votes = 100 where name = ?', ['John']
 
 //运行删除语句:返回删除的行数
 DB::delete("delete from users");
 
 
 //监听查询服务
class AppServiceProvider extends ServiceProvider{
    /**
     * 启动所有应用服务
     *
     * @return void
     */
    public function boot()
    {
        DB::listen(function($query) {
            // $query->sql
            // $query->bindings
            // $query->time
        });
    }

}


数据库事务:


/**

想要在一个数据库事务中运行一连串操作,

可以使用DB门面的transaction方法,

如果事务闭包中抛出异常,事务将会自动回滚

。如果闭包执行成功,事务将会自动提交。

使用transaction方法时不需要担心手动回滚或提交:

**/

自动事务:

DB::transaction(function () {
    DB::table('users')->update(['votes' => 1]);
    DB::table('posts')->delete();
});

手动事务:

DB::beginTransaction();

DB::rollBack();

DB::commit();

//使用DB门而的事务方法还可以用于控制查询构造器和Eloquent ORM的事务。

 

 DB::table("user")



 构造器:

 DB::table("users")->get();   使用get方法获取表中所有记录


 ->first() 方法 获取表中的一行数据



 得到email的值

 ->value("email") 得到表中这一行数据email的值


//获取数据列值列表

 ->lists("title");

->lists("title","name");

->lists(["title","name"]);

  


distinct方法允许你强制查询返回不重复的结果集:


//得到这条数据 只返回一条

//$db=DB::connection("newcimie")->table("articlenav")->where("id",1)->first();


//返回这条数据的classname 这个值。

//$db=DB::connection("newcimie")->table("articlenav")->where("id",1)->value("classname");


//dd($db);


//聚合函数

//队列构建器还提供了很多聚合方法,比如count, max, min, avg, 和 sum,你可以在构造查询之后调用这些方法:

/*$users = DB::table('users')->count();

$price = DB::table('orders')->max('price');*/

//当然,你可以联合其它查询子句和聚合函数来构建查询:

/* $price = DB::table('orders')

     ->where('finalized', 1)

     ->avg('price');*/


//$users = DB::connection("newcimie")->table('articlenav')->select('id', 'classname as title')->get();

$users = DB::connection("newcimie")->table('articlenav')->select('id', 'classname as title')->where("pid",1)->get();

dd($users);



连接join()

$users = DB::table('users')
            ->join('contacts', 'users.id', '=', 'contacts.user_id')
            ->join('orders', 'users.id', '=', 'orders.user_id')
            ->select('users.*', 'contacts.phone', 'orders.price')
            ->get();

$data=DB::connection("newcimie")->table("article")

            ->join("articlenav","article.nav","=","articlenav.id")

            ->select("article.title","article.id","article.nav","articlenav.classname")

            ->where("article.nav","=",9)

            ->get();



where


$users = DB::table('users')
                ->where('votes', '>=', 100)
                ->get();

$users = DB::table('users')
                ->where('votes', '<>', 100)
                ->get();

$users = DB::table('users')
                ->where('name', 'like', 'T%')
                ->get();
$users = DB::table('users')
                    ->whereBetween('votes', [1, 100])->get();
$users = DB::table('users')
                    ->whereNotBetween('votes', [1, 100])
                    ->get();

 

$users = DB::table('users')
                    ->whereIn('id', [1, 2, 3])
                    ->get();

 

$users = DB::table('users')
                    ->whereNotIn('id', [1, 2, 3])
                    ->get();


7、排序、分组、限定

orderBy方法对结果进行排序,

orderBy的第一个参数应该是你希望排序的列,第二个参数控制着排序的方向——asc或desc:

$users = DB::table('users')
                ->orderBy('name', 'desc')
                ->get();


groupBy / having / havingRaw

groupByhaving方法用于对结果集进行分组,having方法和where方法的用法类似:

$users = DB::table('users')
                ->groupBy('account_id')
                ->having('account_id', '>', 100)
                ->get();

havingRaw方法可以用于设置原生字符串作为having子句的值,例如,我们要找到所有售价大于$2500的部分:

$users = DB::table('orders')
                ->select('department', DB::raw('SUM(price) as total_sales'))
                ->groupBy('department')
                ->havingRaw('SUM(price) > 2500')
                ->get();


8、插入(insert)

插入数据

$_data=Input::all();

$_data=Input::export("_token");

DB::table("users")->insert($_data);


DB::table('users')->insert(
    ['email' => 'taylor@example.com', 'votes' => 0]
 );


DB::table('users')->insert([
    ['email' => 'taylor@example.com', 'votes' => 0],
    ['email' => 'dayle@example.com', 'votes' => 0]
]);


$_data 这个可以是一个一维数组,也可是二维数组同时插入多个数据。


如果数据表中有自增ID,使用insertGetId() 方法来插入记录将返回ID值

DB::table("Users")->insertGetId($_data); 


//注意:当使用PostgresSQLinsertGetId方法默认自增列被命名为id

//如果你想要从其他“序列”获取ID,可以将序列名作为第二个参数传递到insertGetId方法。





9、更新(Update)

$_array=["key"=>value];   这是要更新的数据

使用where 来约束要更新的数据

DB::table("users")->where("id",1)->update($_array);



10、删除(delete)

DB::table("users")->delete();

DB::connection("newcimie")->table("users")->where("id",11)->delete();

db::table("users")->where("id","<","100")->delete();


也可以使用

DB::table("users")->truncate();



可以使用这句代码,打印出最后的sql语句:


DB::getQueryLog()



11、悲观锁


共享锁可以避免被选择的行被修改直到事务提交:

sharedLock()


lockForUpdate() 这个锁可以避免选择行被其他共享锁修改或删除