laravel
php artisan migrate //执行数据库的迁移操作
提供了php cli 方式进行创建model类,负责与数据库交互
php artisan make:model Page
php artisan make:controller Admin/AdminHomeController
ORM:即'Object Relational Mapping' 对象关系映射,ORM出现是为了帮我们把对数据库的操作变得更加方便
要在数据库交易运行一组操作,你可以在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_at
和 updated_at
字段如果你不希望让 Eloquent 来自动维护这两个字段,在你的模型内将 $timestamps
属性设置为 false
如果需要自定义你的时间戳格式,在你的模型内设置$dateFormat
属性,这个属性决定了日期在数据库中如何保存
DB::table('表名')->get() 获取数据库所有字段的信息
从数据表中取得单一列或者栏,若你只需从数据表中取出单一列,你可以使用 first
方法。这个方法会返回单一的 StdClass
对象:
DB::table('grades')->where('username','jack')->first()
从数据表中将结果切块:使用chunk
方法,这个方法一次取出一小块结果,并将每个区块喂给一个闭包处理
DB::table('grades')->chunk(100, function($users) {
foreach ($users as $user) {
echo $user->username //not $user['username'];
}
});
可以对闭包的结果返回false
已停止对后续的操作
聚合:查询构建器提供了多种聚合方法: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 的操作
来源:oschina
链接:https://my.oschina.net/u/2380832/blog/650061