laravel学习(一)

laravel
php artisan migrate //执行数据库的迁移操做

提供了php cli 方式进行建立model类,负责与数据库交互php

php artisan make:model Page
php artisan make:controller Admin/AdminHomeController

ORM:即'Object Relational Mapping' 对象关系映射,ORM出现是为了帮咱们把对数据库的操做变得更加方便laravel

要在数据库交易运行一组操做,你能够在DB facade 使用transaction方法. 若是闭包运行成功,交易将会自动提交数据库

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

若是你想手动处理交易而且彻底控制还原或提交,你能够在DB facade 使用 beginTransaction数组

DB::beginTransaction();
//还原
DB::rollBack();
//提交
DB::commit();

获取pdo实例$pdo = DB::connection()->getPdo();闭包

默认状况下,Eloquent 预期你的数据表会有 created_atupdated_at 字段若是你不但愿让 Eloquent 来自动维护这两个字段,在你的模型内将 $timestamps 属性设置为 falseapp

若是须要自定义你的时间戳格式,在你的模型内设置$dateFormat属性,这个属性决定了日期在数据库中如何保存函数

DB::table('表名')->get()  获取数据库全部字段的信息

从数据表中取得单一列或者栏,若你只需从数据表中取出单一列,你能够使用 first 方法。这个方法会返回单一的 StdClass 对象:post

DB::table('grades')->where('username','jack')->first()

从数据表中将结果切块:使用chunk方法,这个方法一次取出一小块结果,并将每一个区块喂给一个闭包处理ui

DB::table('grades')->chunk(100, function($users) {
    foreach ($users as $user) {
        echo $user->username //not $user['username'];
    }
});

能够对闭包的结果返回false已中止对后续的操做rest

聚合:查询构建器提供了多种聚合方法:count,max,min,avg,sum能够在查找后调用任何一个方法

$data = DB::table('grades')->count();
$data = DB::table('grades')->max();
$data = DB::table('grades')->min();

能够使用select方法为查找一个自定义的select子句

$user = DB::table('grades')->select('username','username as qq')->get();

distinct容许你强制让查找传回不重复的结果

$data = DB::table('grades')->distinct()->get()

若已经有一个查询构建器的实例,但愿在既存的select子句加入一个字段,你能够使用addSelect方法

$query = DB::table('grades')->select('username')

$users = $query->addSelect('sex')->get();

Inner join 语法 查询构建器也能够编写join语法,传入join的方法的第一个参数是你须要链接的数据表的名称,其余参数则用以链接的字段约束,能够在单一查找链接多个数据表

$user = DB::table('grades')
		->join('表名','grades.id','=','表名.id')
		->join('表名1','grades.sex','=','表名1.sex')
		->get()

		左链接,右链接同理

where 子句:

经过where 来增长查询条件

$users = DB:table('grades')->where('username','=','jack')->get()

也能够使用其余运算符号
$users = DB:table('grades')->where('id','>=','12')->get()
//不等于
$users = DB:table('grades')->where('username','<>','jack')->get()
//like
$users = DB:table('grades')->where('username','like','q%')->get()

//使用orwhere

$users = DB::table('grades')>where('id','>','24')>orWhere('username','gewenrui2')->get();

其余的where子句

  • whereBetween 方法验证一个字段的值介于两个值之间
  • whereNotBetween 方法验证一个字段的值落在两个值以外
  • whereIn 方法验证给定字段的值包含在给定的数组以内
  • whereNotIn 方法验证给定字段的值不包含在给定的数组以内
  • whereNull 方法验证给定㯗位的值为 NULL
  • whereNotNull 方法验证一个字段的值不为 NULL

高端where子句:

$users = DB::table('grades')->where('username','=','gewenrui2')
->orWhere(function($query){$query
->where('id','>=','22')
->where('sex','=','nan');
			})->get();

至关于
		//select * from grades where username = 'gewenrui2' or(id >=22 and sex = nan)

whereExits 方法容许你编写SQL子句,whereExits接受一个闭包参数

DB::table('users')
            ->whereExists(function ($query) {
                $query->select(DB::raw(1))
                      ->from('orders')
                      ->whereRaw('orders.user_id = users.id');
            })
            ->get();

//至关于          
select * from users where exits(select 1 from orders.user_id = users_id)

为查找的结果分组

$users = DB::table('grades')
			->groupBy('username')
			->having('id','>=',22)->get();

		//select * from grades group by username having id >=22

skip 与 take

要限制查找所返回的结果数量,或略过给定数量的查找结果(偏移),你可以使用 skip 和 take 方法:

$users = DB::table('users')->skip(10)->take(5)->get();

Insert

insert接受一个数组,包含要插入的字段名称以及值

$users = DB::table('grades')->insert(
			['username' => 'wenruige',
			 'stu_id'   => 1330090604,
			 'sex'      => 'male',
			 'grade'	=> 100
			]
		);
	若数据表有一自动递增的 id,使用 insertGetId 方法来插入记录并取得其 ID:

		$users = DB::table('grades')->insertGetId(
			['username' => 'wenruige',
			 'stu_id'   => 1330090604,
			 'sex'      => 'male',
			 'grade'	=> 100
			]
		);

Updates:可以使用 update 方法让查找产生器更新已存在的记录。update 方法和 insert 方法同样,接受含一对字段及值的数组,其中包含要被更新的字段。你能够使用 where 子句来约束 update 查找

DB::table('grades')->where('sex','male')->update(['username' => 'qq']);

Delete:将记录从表中删除

//删除一个文件
DB::table('grades')->delete()
//经过限制条件来定向删除记录
DB::table('grades')->where('id','=',21)->delete();
//若你但愿截去整个数据表来移除全部数据列,并将自动递增 ID 重设为零,你能够使用 truncate 方法
DB::table('grades')->truncate();

悲观锁定 产询产生器也包含一些函数,用以协助你在 select 语法上做「悲观锁定」。要以「共享锁」来运行述句,你能够在查找上使用 sharedLock 方法。共享锁可避免选择的数据列被更改,直到你的交易提交为止:

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

此外,你能够使用 lockForUpdate 方法。「用以更新」锁可避免数据列被其余共享锁修改或选取:

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

找不到的例外:

findOrFail以及firstOrFail方法会返回查找的第一个结果,将会抛出一个异常

若是没有捕捉到意外,会自动返回HTTP404回应给用户,因此当使用这些方法时,没有必要明确的编写404回应

添加和更新模型

要在数据库中建立一条新记录,只要建立一个新模型实例,并在模型上设置属性,再调用 save 方法

$flight = new Flight;

$flight->name = $request->name;

$flight->save();
当 save 方法被调用时,created_at 以及 updated_at 时间戳记将会自动被设置,因此不须要手动去设置它们。

save 方法也能够用于更新数据库中已经存在的模型。要更新模型,你必须先取回模型,设置任何你但愿更新的属性,接着调用 save 方法。一样的,updated_at 时间戳记将会自动被更新,因此不须要手动设置它的值

$flight = App\Flight::find(1);

$flight->name = 'New Flight Name';

$flight->save();

批量赋值

须要在你的模型上指定一个 fillable 或 guarded 属性,由于全部的 Eloquent 模型有针对批量赋值(Mass-Assignment)作保护。

protected $fillable = ['name'];

$fillable做为一个可批量赋值属性的白名单,$guarded更像是黑名单

删除模型

删除模型在实例上调用delete方法

$data = App\Data::find(1);
$data->delete();

透过键来删除现有的模型:

咱们在调用delete模型,先从数据库取回了模型,若是知道了主键就能够不取回模型直接删除它

App\Data::destroy(1)
App\Data::destroy([1,2,3])

经过查找来删除模型

App\Data::where('name',1)->delete();

软删除

除了实际从数据库中移除记录,Eloquent 也能够「软删除」模型。当模型被软删除时,它们不是真的从数据库中被移除。而是 deleted_at 属性被设置在模型上并添加到数据库。若是模型有一个非空值的 deleted_at,表明模型已经被软删除了。要在模型启动软删除,必须在模型上使用

use SoftDeletes;   
protected $dates = ['deleted_at'];

被软删除的模型将会自动从全部的查找结果中排除。然而,你能够借由在查找上调用 withTrashed 方法, 强迫被软删除的模型出如今查找结果

$flights = App\Data::withTrashed()
                ->where('id', 1)
                ->get();

时候你可能但愿「取消删除」一个被软删除的模型。要恢复一个被软删除的模型回到有效状态,必须在模型实例上使用 restore 方法

$flight->restore();

当一个新模型初次被保存,将会触发 creating 以及 created 事件。若是一个模型已经存在于数据库并且调用了 save 方法,将会触发 updating 和 updated 事件。然而,在这两个情况下,都将会触发 saving 和 saved 事件。

public function boot()
    {
        User::creating(function ($user) {
            if ( ! $user->isValid()) {
                return false;
            }
        });
    }

咱们来在服务提供者中定义一个 Eloquent 事件监听器。在咱们的事件监听器中,咱们会在给定的模型上调用 isValid 方法,并在模型无效的时候返回 false。从 Eloquent 事件监听器返回 false 会取消 save 和 update 的操做

相关文章
相关标签/搜索