快速入门替换表名protected$table='my_flights';替换主键名称protected$primaryKey='id';注意:Eloquent默认的主键字段是一个自增的整型数据,也就是说主键会自动转为int类型,如果要使用非自增或者非数字的主键,必须在对应模型中将$incrementing属性设置为false,如果主键不是整数,还必须将$keyType属性值设置为string。关闭时间戳记录public$timestamps=false;获取模型数据//Eloquent的all方法返回模型表中的所有结果$flights=App\Flight::all();foreach($flightsas$flight){echo$flight->name;}//添加约束$flights=App\Flight::where('active',1)->orderBy('name','desc')->取(10)->获取();获取单个模型//通过主键获取模型$flight=App\Flight::find(1);//获取第一个符合查询条件的模型$flight=App\Flight::where('active',1)->first();//传递主键数组调用find方法,返回匹配记录集合$flights=App\Flight::find([1,2,3]);获取聚合结果$count=App\Flight::where('active',1)->count();$max=App\Flight::where('active',1)->max('price');插入记录$flight=newFlight;$flight->name=$request->name;$flight->save();更新模型$flight=App\Flight::find(1);$flight->name='NewFlightName';$flight->节省();批量更新App\Flight::where('active',1)->where('destination','SanDiego')->update(['delayed'=>1]);deletemodel//删除$flight=App\Flight::find(1);$flight->delete();//通过主键删除模型App\Flight::destroy(1);App\Flight::destroy([1,2,3]);App\Flight::destroy(1,2,3);//通过查询删除模型$deletedRows=App\Flight::where('active',0)->delete();软删除//EloquentModeluseIlluminate\Database\Eloquent\Model;useIlluminate\Database\Eloquent\SoftDeletes;classFlightextendsModel{useSoftDeletes;/***应该调整为日期的属性**@vararray*/protected$dates=['deleted_at'];}//添加deleted_at列到数据表结构Schema::table('flights',function($table){$table->softDeletes();});//判断给定模型实例是否被删除软删除,可以使用trashed方法if($flight->trashed()){//...}//查询软删除模型$flights=App\Flight::withTrashed()->where('account_id',1)->get();$flight->history()->withTrashed()->get();//只获取软删除模型$flights=App\Flight::onlyTrashed()->where('airline_id',1)->get();//恢复被软删除的模型$flight->restore();//使用restore方法快速恢复多个模型而不触发任何模型事件App\Flight:::withTrashed()->where('airline_id',1)->restore();$flight->history()->restore();本地范围/***查询范围仅包括活跃用户**@return\Illuminate\Database\Eloquent\Builder*/publicfunctionscopePopular($query){return$query->where('votes','>',100);}/***仅包含活跃用户的查询函数域**@return\Illuminate\Database\Eloquent\Builder*/publicfunctionscopeActive($query){return$query->where('active',1);}//使用局部作用域$users=App\User::popular()->active()->orderBy('created_at')->get();动态范围/***让查询只包含给定类型的用户**@param\Illuminate\Database\Eloquent\Builder$query*@参数混合$type*@return\Illuminate\Database\Eloquent\Builder*/publicfunctionscopeOfType($query,$type){return$query->where('type',$type);}//使用动态作用域$users=App\User::ofType('admin')->get();模型关联一对一关联//有类UserextendsModel{/***获取用户关联的手机*/publicfunctionphone(){//Phone:关联模型//Phone:user_id外键//User:id主键return$this->hasOne('App\Phone','user_id','id');}}//BelongingclassPhoneextendsModel{/***获取拥有手机的用户*/publicfunctionuser(){//User:所属模型//Phone:user_id外键//User:id父模型主键返回$this->belongsTo('App\User','user_id','id');}}//空模型类ArticleextendsModel{/***获取文章作者*/publicfunctionuser(){return$this->belongsTo('App\User')->withDefault(function($user){$user->name='客座作者';});}}一对多关联//有类PostextendsModel{/***获取博文评论*/publicfunctioncomments(){//Comment:关联模型//Comment:post_id外键//Post:id主键返回$this->hasMany('App\Comment','post_id','id');}}//属于Comm类entextendsModel{/***获取评论对应的博文*/publicfunctionpost(){//Post:关联模型//Comment:post_id外键//Post:id父模型主键return$this->belongsTo('App\Post','post_id','id');}}多对多关联//关联类UserextendsModel{/***用户角色*/publicfunctionroles(){//角色:关联模型//user_roles:中间表名//user_id:对应模型主键//role_id:对应关联的主键return$this->belongsToMany('App\Role','user_roles','user_id','role_id');}}//获取中间表字段,通过pivot属性$user=App\User::find(1);foreach($user->rolesas$role){echo$role->pivot->created_at;}//当数据透视表包含附加属性时,必须指定return$this->belongsToMany('App\Role')->withPivot('column1','column2');//自动包含created_at和updated_atreturn$this->belongsToMany('App\Role')->withTimestamps();//将pivot更改为订阅以提高可读性return$this->belongsToMany('App\Podcast')->as('subscription')->withTimestamps();$users=User::with('podcasts')->get();foreach($users->flatMap->podcastsas$podcast){echo$podcast->subscription->created_at;}预加载//select*frombooks$books=App\Book::all();//select*fromauthorswhereidin(1,2,3,4,5,...)$books=App\Book::with('author')->get();foreach($booksas$book){echo$book->author->name;}//预加载多个Relationship$books=App\Book::with('author','publisher')->get();//嵌套预加载$books=App\Book::with('author.contacts')->get();//急于加载指定字段//注意:使用该功能时,必须列出id字段$users=App\Book::with('author:id,name')->get();//条件预加载$users=App\User::with(['posts'=>function($query){$query->where('title','like','%first%');}])->获取();Insert/updateassociatedmodel//Insertassociatedmodel$comment=newApp\Comment(['message'=>'Anewcomment.']);$post=App\Post::find(1);//调用comments方法获取关系实例,save会在Comment模型中将post_id添加到$post->comments()->save($comment);//保存多个关联模型$post=App\Post::find(1);$post->comments()->saveMany([newApp\Comment(['message'=>'Anewcomment.']),newApp\Comment(['message'=>'Anothercomment.']),]);//使用create创建,与save的区别在于,它接收一个关联数组,create方法遵循模型属性的批量赋值$post=App\Post::find(1);$comment=$post->comments()->create(['message'=>'一条新评论。',]);//保存多个关联模型$post=App\Post::find(1);$post->comments()->createMany([['message'=>'Anewcomment.',],['message'=>'Anothernewcomment.',],]);//更新从属关系(belongsTo)$account=App\Account::find(10);//关联方法外键会在子模型中设置$user->account()->associate($account);$user->save();//移除关联(belongsTo)//dissociate方法会设置关联关系的外键为空$user->account()->分离();$用户->保存();attach/detachmany-to-manyassociationmodel$user=App\User::find(1);//在joinmodel的中间Insertrecordsintothetable$user->roles()->attach($roleId);//插入数据和附加数组到中间表$user->roles()->attach($roleId,['expires'=>$expires]);//从中间表中移除对应的记录:指定移除角色的用户$user->roles()->detach($roleId);//从中间表中移除对应记录:指定用户移除所有角色$user->roles()->detach();//attach和detach也接收一个ID数组作为输入$user=App\User::find(1);$user->roles()->detach([1,2,3]);$user->roles()->attach([1=>['expires'=>$expires],2=>['expires'=>$expires]]);当在中间表上保存额外数据以处理多对多关联时,save方法接收一个中间表数组作为第二个参数:App\User::find(1)->roles()->save($角色,['expires'=>$expires]);访问器和修饰符访问器和修饰符允许您访问模型属性或设置它们的值FormattingEloquent属性。例如,您可能希望使用Laravel加密器来加密存储在数据库中的数据,并在Eloquent模型中访问时自动解密。除了自定义访问器和修饰符,Eloquent还可以自动将日期字段转换为Carbon实例,甚至可以将文本转换为JSON。AccessorclassUserextendsModel{/***获取用户的名字**@paramstring$value*@returnstring*/publicfunctiongetFirstNameAttribute($value){returnucfirst($value);}/***获取用户全名**@returnstring*/publicfunctiongetFullName属性(){返回“{$this->first_name}{$this->last_name}”;}}//访问first_name属性$firstName=App\User::find(1)->first_name;modifierclassUserextendsModel{/***设置用户的名字**@paramstring$value*@returnstring*/publicfunctionsetFirstNameAttribute($value){$this->attributes['first_name']=strtolower($价值);}}//设置名字属性App\User::find(1)->first_name='Sally';date修饰符默认情况下,Eloquent会将created_at和updated_at列转换为Carbon实例,它继承自PHP原生的Datetime类,并提供了多种有用的方法。可以自定义哪些字段自动调整,甚至可以通过重写模型中的$dates属性来完全禁止调整:classUserextendsModel{/***shouldbeadjustedAttributesfordates**@vararray*/protected$dates=['created_at','updated_at','disabled_at'];}//自动转换存入数据库$user=App\User::find(1);$user->disabled_at=Carbon::now();$user->save();//使用Carbon提供的方法$user=App\User::find(1);return$user->disabled_at->getTimestamp();模型日期格式默认时间戳格式为Y-m-dH:i:s,可以结合$dateFormat属性自定义格式:classFlightextendsModel{/***模型日期的存储格式**@varstring*/protected$dateFormat='U';}属性转换支持的转换类型:integer,real,float,double,string,boolean,object,array,collection,date,datetimeandtimestamp。如果数据库有JSON或TEXT字段类型包含序列化的JSON,可以使用数组转换,会自动序列化和反序列化。classUserextendsModel{/***应该转换为原生类型的属性**@vararray*/protected$casts=[//convertis_adminproperty:convertfrominteger(0/1)toboolean'is_admin'=>'boolean',//访问options属性将自动从JSON反序列化为PHP数组//设置options属性的值,给定的数组将自动转换为JSON进行存储'options'=>'array',];}//is_admin属性已经转换:if($user->is_admin){//}//自动序列化和反序列化$user=App\User::find(1);$options=$user->options;$options['key']='value';$user->options=$options;$user->save();文章来自本人博客,发表于2018-06-10,
