图片上的是手机上的,什么软件2018安卓应用商店排名???

Laravel & Lumen之Eloquent ORM使用速查-高级部分 - 推酷
Laravel & Lumen之Eloquent ORM使用速查-高级部分
查询作用域
全局作用域
全局作用域允许你对给定模型的所有查询添加约束。使用全局作用域功能可以为模型的所有操作增加约束。
软删除功能实际上就是利用了全局作用域功能
实现一个全局作用域功能只需要定义一个实现
Illuminate\Database\Eloquent\Scope
接口的类,该接口只有一个方法
,在该方法中增加查询需要的约束
namespace App\S
use Illuminate\Database\Eloquent\S
use Illuminate\Database\Eloquent\M
use Illuminate\Database\Eloquent\B
class AgeScope implements Scope
public function apply(Builder $builder, Model $model)
return $builder-&where('age', '&', 200);
在模型的中,需要覆盖其
方法,在该方法中增加
addGlobalScope
namespace A
use App\Scopes\AgeS
use Illuminate\Database\Eloquent\M
class User extends Model
protected static function boot()
parent::boot();
static::addGlobalScope(new AgeScope);
添加全局作用域之后,
User::all()
操作将会产生如下等价sql
select * from `users` where `age` & 200
也可以使用匿名函数添加全局约束
static::addGlobalScope('age', function(Builder $builder) {
$builder-&where('age', '&', 200);
查询中要移除全局约束的限制,使用
withoutGlobalScope
// 只移除age约束
User::withoutGlobalScope('age')-&get();
User::withoutGlobalScope(AgeScope::class)-&get();
// 移除所有约束
User::withoutGlobalScopes()-&get();
// 移除多个约束
User::withoutGlobalScopes([FirstScope::class, SecondScope::class])-&get();
本地作用域
本地作用域只对部分查询添加约束,需要手动指定是否添加约束,在模型中添加约束方法,使用前缀
namespace A
use Illuminate\Database\Eloquent\M
class User extends Model
public function scopePopular($query)
return $query-&where('votes', '&', 100);
public function scopeActive($query)
return $query-&where('active', 1);
使用上述添加的本地约束查询,只需要在查询中使用
前缀的方法,去掉
$users = App\User::popular()-&active()-&orderBy('created_at')-&get();
本地作用域方法是可以接受参数的
public function scopeOfType($query, $type)
return $query-&where('type', $type);
调用的时候
$users = App\User::ofType('admin')-&get();
Eloquent模型会触发下列事件
假设我们希望保存用户的时候对用户进行校验,校验通过后才允许保存到数据库,可以在服务提供者中为模型的事件绑定监听
namespace App\P
use Illuminate\Support\ServiceP
class AppServiceProvider extends ServiceProvider
public function boot()
User::creating(function ($user) {
if ( ! $user-&isValid()) {
public function register()
上述服务提供者对象中,在框架启动时会监听模型的
事件,当保存用户之间检查用户数据的合法性,如果不合法,返回false,模型数据不会被持久化到数据。
返回false会阻止模型的
当构建JSON API的时候,经常会需要转换模型和关系为数组或者json。Eloquent提供了一些方法可以方便的来实现数据类型之间的转换。
转换模型/集合为数组 - toArray()
$user = App\User::with('roles')-&first();
return $user-&toArray();
$users = App\User::all();
return $users-&toArray();
转换模型为json - toJson()
$user = App\User::find(1);
return $user-&toJson();
$user = App\User::find(1);
return (string) $
有时某些字段不应该被序列化,比如用户的密码等,使用
字段控制那些字段不应该被序列化
namespace A
use Illuminate\Database\Eloquent\M
class User extends Model
protected $hidden = ['password'];
隐藏关联关系的时候,使用的是它的方法名称,不是动态的属性名
也可以使用
指定会被序列化的白名单
namespace A
use Illuminate\Database\Eloquent\M
class User extends Model
protected $visible = ['first_name', 'last_name'];
有时可能需要某个隐藏字段被临时序列化,使用
makeVisible
return $user-&makeVisible('attribute')-&toArray();
为json追加值
有时需要在json中追加一些数据库中不存在的字段,使用下列方法,现在模型中增加一个get方法
namespace A
use Illuminate\Database\Eloquent\M
class User extends Model
protected $appends = ['is_admin'];
public function getIsAdminAttribute()
return $this-&attributes['admin'] == 'yes';
方法签名为
getXXXAttribute
格式,然后为模型的
字段设置字段名。
在Eloquent模型中,Accessor和Mutator可以用来对模型的属性进行处理,比如我们希望存储到表中的密码字段要经过加密才行,我们可以使用Laravel的加密工具自动的对它进行加密。
Accessors & Mutators
要定义一个accessor,需要在模型中创建一个名称为
getXxxAttribute
的方法,其中的Xxx是驼峰命名法的字段名。
假设我们有一个字段是
first_name
,当我们尝试去获取first_name的值的时候,
getFirstNameAttribute
方法将会被自动的调用
namespace A
use Illuminate\Database\Eloquent\M
class User extends Model
public function getFirstNameAttribute($value)
return ucfirst($value);
在访问的时候,只需要正常的访问属性就可以
$user = App\User::find(1);
$firstName = $user-&first_
创建mutators与accessorsl类似,创建名为
setXxxAttribute
的方法即可
namespace A
use Illuminate\Database\Eloquent\M
class User extends Model
public function setFirstNameAttribute($value)
$this-&attributes['first_name'] = strtolower($value);
$user = App\User::find(1);
$user-&first_name = 'Sally';
属性提供了一种非常简便的方式转换属性为常见的数据类型,在模型中,使用
属性定义一个数组,该数组的key为要转换的属性名称,value为转换的数据类型,当前支持
collection
namespace A
use Illuminate\Database\Eloquent\M
class User extends Model
protected $casts = [
'is_admin' =& 'boolean',
数组类型的转换时非常有用的,我们在数据库中存储json数据的时候,可以将其转换为数组形式。
namespace A
use Illuminate\Database\Eloquent\M
class User extends Model
protected $casts = [
'options' =& 'array',
从配置数组转换的属性取值或者赋值的时候都会自动的完成json和array的转换
$user = App\User::find(1);
$options = $user-&
$options['key'] = 'value';
$user-&options = $
$user-&save();
已发表评论数()
请填写推刊名
描述不能大于100个字符!
权限设置: 公开
仅自己可见
正文不准确
标题不准确
排版有问题
主题不准确
没有分页内容
图片无法显示
视频无法显示
与原文不一致laravel 5 中Eloquent的属性类型转换真是太棒了!Laravel & Lumen之Eloquent ORM使用速查-基础部分
(window.slotbydup=window.slotbydup || []).push({
id: '2611110',
container: s,
size: '240,200',
display: 'inlay-fix'
您当前位置: &
[ 所属分类
| 时间 2016 |
作者 红领巾 ]
使用Eloquent ['elkwnt]
时,数据库查询构造器的方法对模型类也是也用的,使用上只是省略了 DB::table('表名')
在模型中使用protected成员变量 $table
指定绑定的表名。
namespace A
use Illuminate\Database\Eloquent\M
class Flight extends Model
protected $table = 'my_flights';
Eloquent 假设每个表都有一个名为 id
的主键,可以通过 $primaryKey
成员变量覆盖该字段名称,另外,Eloquent假设主键字段是自增的整数,如果你想用非自增的主键或者非数字的主键的话,必须指定模型中的public属性 $incrementing
默认情况下,Eloquent期望表中存在 created_at
和 updated_at
两个字段,字段类型为 timestamp
,如果不希望这两个字段的话,设置 $timestamps
namespace A
use Illuminate\Database\Eloquent\M
class Flight extends Model
public $timestamps =
protected $dateFormat = 'U';
使用 protected $connection = 'connection-name'
指定模型采用的数据库连接。
基本查询操作
用于返回模型表中所有的结果
$flights = Flight::all();
foreach ($flights as $flight) {
echo $flight-&
也可以使用 get
方法为查询结果添加约束
$flights = App\Flight::where('active', 1)
-&orderBy('name', 'desc')
-&take(10)
可以看到,查询构造器的方法对模型类也是可以使用的
在eloquent ORM中, get
方法查询出多个结果集,它们的返回值是一个 Illuminate\Database\Eloquent\Collection
对象,该对象提供了多种对结果集操作的方法
public function find($key, $default = null);
public function contains($key, $value = null);
public function modelKeys();
public function diff($items)
该对象的方法有很多,这里只列出一小部分,更多方法参考API文档 Collection
和 使用说明文档
对大量结果分段处理,同样是使用 chunk
Flight::chunk(200, function ($flights) {
foreach ($flights as $flight) {
查询单个结果
方法查询单个结果,返回的是单个的模型实例
// 通过主键查询模型...
$flight = App\Flight::find(1);
// 使用约束...
$flight = App\Flight::where('active', 1)-&first();
方法也可以返回多个结果,以 Collection
对象的形式返回,参数为多个主键
$flights = App\Flight::find([1, 2, 3]);
如果查询不到结果的话,可以使用 findOrFail
或者 firstOrFail
方法,这两个方法在查询不到结果的时候会抛出 Illuminate\Database\Eloquent\ModelNotFoundException
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '&', 100)-&firstOrFail();
如果没有捕获这个异常的话,laravel会自动返回给用户一个 404
的响应结果,因此如果希望找不到的时候返回 404
,是可以直接使用该方法返回的
Route::get('/api/flights/{id}', function ($id) {
return App\Flight::findOrFail($id);
查询聚集函数结果
与查询构造器查询方法一样,可以使用聚集函数返回结果,常见的比如 max
$count = App\Flight::where('active', 1)-&count();
$max = App\Flight::where('active', 1)-&max('price');
分页查询可以直接使用 paginate
LengthAwarePaginator paginate(
int $perPage = null,
array $columns = array('*'),
string $pageName = 'page',
int|null $page = null
每页显示数量
查询的列名
页码参数名称
返回值为 LengthAwarePaginator
$limit = 20;
$page = 1;
return Enterprise::paginate($limit, ['*'], 'page', $page);
基本插入操作
插入新的数据只需要创建一个新的模型实例,然后设置模型属性,最后调用 save
$flight = new F
$flight-&name = $request-&
$flight-&save();
在调用 save
方法的时候,会自动为 created_at
和 updated_at
字段设置时间戳,不需要手动指定
批量赋值插入
使用 create
方法可以执行批量为模型的属性赋值的插入操作,该方法将会返回新插入的模型,在执行 create
方法之前,需要先在模型中指定 fillable
和 guarded
属性,用于防止不合法的属性赋值(例如避免用户传入的is_admin属性被误录入数据表)。
指定 $fillable
属性的目的是该属性指定的字段可以通过 create
方法插入,其它的字段将被过滤掉,类似于白名单,而 $guarded
则相反,类似于黑名单。
protected $fillable = ['name'];
protected $guarded = ['price'];
执行 create
操作就只有白名单或者黑名单之外的字段可以更新了
$flight = App\Flight::create(['name' =& 'Flight 10']);
除了 create
方法,还有两外两个方法可以使用 firstOrNew
和 firstOrCreate
firstOrCreate
方法用来使用给定的列值对查询记录,如果查不到则插入新的。 fristOrNew
与 firstOrCreate
类似,不同在于如果不存在,它会返回一个新的模型对象,不过该模型是未经过持久化的,需要手动调用 save
方法持久化到数据库。
// 使用属性检索flight,如果不存在则创建...
$flight = App\Flight::firstOrCreate(['name' =& 'Flight 10']);
// 使用属性检索flight,如果不存在则创建一个模型实例...
$flight = App\Flight::firstOrNew(['name' =& 'Flight 10']);
基本更新操作
不仅可以要用来插入新的数据,也可以用来更新数据,只需先使用模型方法查询出要更新的数据,设置模型属性为新的值,然后再 save
就可以更新了, updated_at
字段会自动更新。
$flight = App\Flight::find(1);
$flight-&name = 'New Flight Name';
$flight-&save();
也可使用 update
方法对多个结果进行更新
App\Flight::where('active', 1)
-&where('destination', 'San Diego')
-&update(['delayed' =& 1]);
基本删除操作
使用 delete
方法删除模型
$flight = App\Flight::find(1);
$flight-&delete();
上述方法需要先查询出模型对象,然后再删除,也可以直接使用主键删除模型而不查询,使用 destroy
App\Flight::destroy(1);
App\Flight::destroy([1, 2, 3]);
App\Flight::destroy(1, 2, 3);
使用约束条件删除,返回删除的行数
$deletedRows = App\Flight::where('active', 0)-&delete();
软删除是在表中增加 deleted_at
字段,当删除记录的时候不会真实删除记录,而是设置该字段的时间戳,由Eloquent模型屏蔽已经设置该字段的数据。
要启用软删除,可以在模型中引用 Illuminate\Database\Eloquent\SoftDeletes
这个Trait,并且在 dates
属性中增加 deleted_at
namespace A
use Illuminate\Database\Eloquent\M
use Illuminate\Database\Eloquent\SoftD
class Flight extends Model
protected $dates = ['deleted_at'];
要判断一个模型是否被软删除了的话,可以使用 trashed
if ($flight-&trashed()) {
查询软删除的模型
包含软删除的模型
本文开发(php)相关术语:php代码审计工具 php开发工程师 移动开发者大会 移动互联网开发 web开发工程师 软件开发流程 软件开发工程师
转载请注明本文标题:本站链接:
分享请点击:
1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
人,永远不会珍惜三种人:一是轻易得到的;二是永远不会离开的;三是那个一直对你很好的。但是,往往这三种人一旦离开就永远不会再回来。
手机客户端
,专注代码审计及安全周边编程,转载请注明出处:http://www.codesec.net
转载文章如有侵权,请邮件 admin[at]codesec.netLaravel & Lumen 数据库操作速查
在Laravel中执行数据库操作有两种方式,一种是使用DB外观对象的静态方法直接执行sql查询,另外一种是使用Model类的静态方法(实际上也是Facade的实现,使用静态访问方式访问Model的方法,内部采用了__callStatic魔术方法代理了对成员方法的访问。查询操作基本查询操作使用sql语句执行select查询操作$results = DB::select(&select * from users where id = ?&, [1]);foreach ($results as $res) {
echo $res->}返回结果为数组,数组中每一个值为一个StdClass对象。也可以使用命名绑定,推荐使用这种方式,更加清晰一些$results = DB::select(&select * from users where id = :id&, [&id& => 1]);从数据表中取得所有的数据列$users = DB::table(&users&)->get();foreach ($users as $user){
var_dump($user->name);}从表中查询单行/列使用first方法返回单行数据,该方法返回的是一个stdClass对象$user = DB::table(&users&)->where(&name&, &John&)->first();echo $user->如果只需要一列的值,则可以使用value方法直接获取单列的值$email = DB::table(&users&)->where(&name&, &John&)->value(&email&);从数据表中分块查找数据列该方法用于数据表中有大量的数据的操作,每次从结果集中取出一部分,使用闭包函数进行处理,然后再处理下一部分,该命令一般用于Artisan命令行程序中处理大量数据。DB::table(&users&)->chunk(100, function($users){
foreach ($users as $user)
}});在闭包函数中,如果返回false,则会停止后续的处理。从数据表中查询某一列的列表比如我们希望查询出角色表中所有的title字段值$titles = DB::table(&roles&)->pluck(&title&);foreach ($titles as $title) {
echo $}这里的pluck函数有两个参数Collection pluck( string $column, string|null $key = null)第一个参数为要查询的列,第二个参数是每一列的key$roles = DB::table(&roles&)->pluck(&title&, &name&);foreach ($roles as $name => $title) {
echo $}聚集函数查询构造器也提供了一些聚集函数如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&);指定select查询条件查询指定的列$users = DB::table(&users&)->select(&name&, &email as user_email&)->get();如果已经指定了select,但是又希望再次添加一些字段,使用它addSelect方法$query = DB::table(&users&)->select(&name&);$users = $query->addSelect(&age&)->get();查询不同的结果distinct$users = DB::table(&users&)->distinct()->get();使用原生表达式使用DB::raw方法可以向查询中注入需要的sql片段,但是非常不推荐使用该方法,用不好会 产生sql注入$users = DB::table(&users&)
->select(DB::raw(&count(*) as user_count, status&))
->where(&status&, &&, 1)
->groupBy(&status&)
->get();Join操作内连接 Inner Join使用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();左连接 Left Join使用leftJoin方法执行左连接操作,参数和join一样$users = DB::table(&users&)
->leftJoin(&posts&, &users.id&, &=&, &posts.user_id&)
高级Join方法如果join方法的约束条件比较复杂,可以使用闭包函数的方式指定DB::table(&users&)
->join(&contacts&, function ($join) {
$join->on(&users.id&, &=&, &contacts.user_id&)->orOn(...);
->get();如果join约束中要使用列值与指定数组比较,则可以使用where和OrWhere方法DB::table(&users&)
->join(&contacts&, function ($join) {
$join->on(&users.id&, &=&, &contacts.user_id&)
->where(&contacts.user_id&, &>&, 5);
->get();Union操作要使用union操作,可以先创建一个query,然后再使用union方法去绑定第二个query$first = DB::table(&users&)
->whereNull(&first_name&);$users = DB::table(&users&)
->whereNull(&last_name&)
->union($first)
->get();同样,unionAll方法也是可以使用的,参数与union相同。Where查询条件简单的wehere条件使用where方法为查询增加where条件,该函数一般需要三个参数:列名,操作符(任何数据库支持的操作符都可以),列值。$users = DB::table(&users&)->where(&votes&, &=&, 100)->get();$users = DB::table(&users&)->where(&votes&, 100)->get();为了方便起见,如果只提供两个参数,则默认第二个参数为=,执行相等匹配。$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();where条件也可以使用数组提供:$users = DB::table(&users&)->where([
[&status&,&1&],
[&subscribed&,&&,&1&],])->get();OR条件如果where条件要使用or操作,则使用orWhere方法$users = DB::table(&users&)
->where(&votes&, &>&, 100)
->orWhere(&name&, &John&)
->get();其它where条件whereBetween / whereNotBetween$users = DB::table(&users&)
->whereBetween(&votes&, [1, 100])->get();$users = DB::table(&users&)
->whereNotBetween(&votes&, [1, 100])->get();whereIn / whereNotIn$users = DB::table(&users&)
->whereIn(&id&, [1, 2, 3])
->get();$users = DB::table(&users&)
->whereNotIn(&id&, [1, 2, 3])
->get();whereNull / whereNotNull$users = DB::table(&users&)
->whereNull(&updated_at&)
->get();$users = DB::table(&users&)
->whereNotNull(&updated_at&)
->get();高级where条件参数组(嵌套条件)DB::table(&users&)
->where(&name&, &=&, &John&)
->orWhere(function ($query) {
$query->where(&votes&, &>&, 100)
->where(&title&, &&, &Admin&);
->get();上述代码等价于下列sqlselect * from users where name = &John& or (votes > 100 and title
&Admin&)whereExists (where exist)DB::table(&users&)
->whereExists(function ($query) {
$query->select(DB::raw(1))
->from(&orders&)
->whereRaw(&orders.user_id = users.id&);
->get();上述代码与下列sql等价select * from userswhere exists (
select 1 from orders where orders.user_id = users.id)JSON类型的列查询MySQL 5.7和Postgres数据库中提供了新的数据类型json,对json提供了原生的支持,使用->可以对json列进行查询。$users = DB::table(&users&)
->where(&options->language&, &en&)
->get();$users = DB::table(&users&)
->where(&preferences->dining->meal&, &salad&)
->get();Ordering, Grouping, Limit, & Offset$users = DB::table(&users&)
->orderBy(&name&, &desc&)
$users = DB::table(&users&)
->groupBy(&account_id&)
->having(&account_id&, &>&, 100)
$users = DB::table(&orders&)
->select(&department&, DB::raw(&SUM(price) as total_sales&))
->groupBy(&department&)
->havingRaw(&SUM(price) > 2500&)
->get();要限制查询返回的结果行数,或者是跳过指定行数的结果(OFFSET),可以使用skip和take方法$users = DB::table(&users&)->skip(10)->take(5)->get();插入操作使用sql语句执行插入插入操作与select操作类似,使用insert函数DB::insert(&insert into users (id, name) values (?, ?)&, [1, &Dayle&]);基本插入操作DB::table(&users&)->insert(
[&email& => &[email protected]&, &votes& => 0]);DB::table(&users&)->insert([
[&email& => &[email protected]&, &votes& => 0],
[&email& => &[email protected]&, &votes& => 0]]);如果希望插入后能够获取新增数据的id,则可以使用insertGetId方法$id = DB::table(&users&)->insertGetId(
[&email& => &[email protected]&, &votes& => 0]);更新操作使用sql语句执行更新操作执行DB中的update后,会返回 操作影响的数据行数DB::update(&update users set votes = 100 where name = ?&, [&John&]);基本更新操作DB::table(&users&)
->where(&id&, 1)
->update([&votes& => 1]);指定列的增减DB::table(&users&)->increment(&votes&);DB::table(&users&)->increment(&votes&, 5);DB::table(&users&)->decrement(&votes&);DB::table(&users&)->decrement(&votes&, 5);在执行自增/减操作的时候,也可以同时更新其它列DB::table(&users&)->increment(&votes&, 1, [&name& => &John&]);删除操作使用sql执行删除执行DB中的delete后,会返回 操作影响的数据行数DB::delete(&delete from users&);基本删除操作DB::table(&users&)->delete();DB::table(&users&)->where(&votes&, &delete();如果希望truncate整个表,则使用truncate方法DB::table(&users&)->truncate();悲观锁使用sharedLock方法可以避免选定的行在事务提交之前被修改DB::table(&users&)->where(&votes&, &>&, 100)->sharedLock()->get();另外lockForUpdate方法可以避免其它的共享锁修改或者是选定DB::table(&users&)->where(&votes&, &>&, 100)->lockForUpdate()->get();事务处理使用transaction方法的callback函数执行事务处理DB::transaction(function(){
DB::table(&users&)->update([&votes& => 1]);
DB::table(&posts&)->delete();});在回调函数中,抛出任何异常都会导致事务回滚如果需要手动管理事务,则使用如下函数DB::beginTransaction();DB::rollback();DB::commit();使用DB类的静态方法启用的事务不仅对普通sql查询有效,对Eloquent ORM同样有效,因为它内部也是调用了DB类的数据库连接。查看日志记录查看请求执行的sql日志记录,需要先执行enableQueryLog开启,然后执行getQueryLog获取DB::connection()->enableQueryLog();$queries = DB::getQueryLog();其它操作执行一般的sql语法DB::statement(&drop table users&);监听查找事件,可以用来对执行的sql进行记录DB::listen(function($sql, $bindings, $time){
// $query->sql
// $query->bindings
// $query->time});获取某个数据库连接$users = DB::connection(&foo&)->select(...);如果还不能满足需求,可以获取PDO对象$pdo = DB::connection()->getPdo();这样不管什么操作都可以做了吧另外含有两个方法,用于重新连接到指定数据库和断开连接DB::reconnect(&foo&);DB::disconnect(&foo&)d;参考: Laravel 5.2 官方文档内容来源:/a/2605
最新教程周点击榜
微信扫一扫

我要回帖

更多关于 安卓市场 的文章

 

随机推荐