这篇文章主要介绍了关于Laravel的Eloquent 模型的介绍,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
Eloquent 模型
默认继承use Illuminate\Database\Eloquent\Model类。
数据表名称与模型名称约定:
数据库的表名一般使用“蛇形命名法”命名。蛇形命名法要求单词小写,单词之间用_下划线连接,且名称是复数。
与之对应的模型名称,则使用“帕斯卡法“命名,即单词头一字母都大写。
如果不是按以上约定,则需指明对应的数据表:
1 2 3 4 5 6 7 | class Flight extends Model
{
protected $table = 'myflights';
}
|
登录后复制
主键:
模型默认数据表用id字段作主键,并且是递增整数类型。这些可以自定义:
1 2 3 4 5 6 7 8 | class Flight extends Model
{
protected $table = 'my_flights'; protected $primaryKey ='mid';
protected $keyType = 'string';
public $incrementing = false;
|
登录后复制
时间截:
模型默认存在created_at 和 updated_at两字段,可设定$timestamps不需两字段:
1 2 3 4 5 | class Flight extends Model
{
public $timestamps = false;
}
|
登录后复制
$dateFormat属性可自定义时间截格式存储在数据表的格式:
1 2 3 4 5 | class Flight extends Model
{
protected $dateFormat = 'U';
}
|
登录后复制
自定义时间截字段名:
1 2 3 | <?phpclass Flight extends Model
{ const CREATED_AT = 'creation_date'; const UPDATED_AT = 'last_update';
}
|
登录后复制
自定义数据库连接:
1 2 3 4 5 | class Flight extends Model
{
protected $connection = 'connection-name';
}
|
登录后复制
模型查询:
1 2 3 4 5 6 | use App\Flight; $flights = App\Flight::all();
foreach ( $flights as $flight ) { echo $flight ->name;
} $flights = App\Flight::where('active', 1)
->orderBy('name', 'desc')
->take(10)
->get();
|
登录后复制
all和get方法返回 Illuminate\Database\Eloquent\Collection实例。
如果查询大批量数据,可使用chunk,可节省内存:
1 2 | Flight::chunk(200, function ( $flights ) { foreach ( $flights as $flight ) {
});
|
登录后复制
或使用游标方法cursor大幅度减少内存的使用:
1 | foreach (Flight::where('foo', 'bar')->cursor() as $flight ) {
|
登录后复制
查询单条数据:
1 2 3 4 5 6 | $flight = App\Flight::where('active', 1)->first();
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
|
登录后复制
聚合查询:
1 | $count = App\Flight::where('active', 1)-> count (); $max = App\Flight::where('active', 1)->max('price');
|
登录后复制
数据更新:
save方法:需要先检索一次,再设置要更新的属性再执行save方法,同时updated_at也会自动更新。
update方法:设置where条件,将更新字段以键值对传入update方法。该更新不会触发saved和updated模型事件。
1 2 3 4 5 | $flight = App\Flight::find(1);
$flight ->name = 'New Flight Name'; $flight ->save();
App\Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);
|
登录后复制
插入数据:
使用模型创建数据,需先设置$fillable或$guarded属性。两属性只能二选一。
1 2 3 4 5 6 7 8 9 10 11 | class Flight extends Model
{
protected $fillable = ['name'];
} class Flight extends Model
{
protected $guarded = ['price'];
}
|
登录后复制
插入数据的方法:
1 2 | $flight = App\Flight::create(['name' => 'Flight 10']);
$flight ->fill(['name' => 'Flight 22']);
|
登录后复制
1 2 3 4 5 6 7 8 9 10 11 12 | $flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);
['name' => 'Flight 10'], ['delayed' => 1]
);
$flight = App\Flight::firstOrNew(['name' => 'Flight 10']);
['name' => 'Flight 10'], ['delayed' => 1]
);
$flight = App\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99]
);
|
登录后复制
firstOrCreate:如果查不到该数据,则根据第一参数和第二参数记录创建记录返回保存的模型;
firstOrNew:如果查不到该数据,则根据第一参数和第二参数记录创建新模型,但并未保存数据,需要手动save才可以保存数据;
updateOrCreate:根据第一参数作条件用更新第二参数数据,如果数据不存在则合并两参数创建记录返回保存的模型。
删除模型:
1 2 3 4 5 6 | $flight = App\Flight::find(1); $flight -> delete ();
App\Flight::destroy([1, 2, 3]);
App\Flight::destroy(1, 2, 3);
$deletedRows = App\Flight::where('active', 0)-> delete ();
|
登录后复制
批量删除时,deleted和deleting模型事件不会被触发。
软删除:
数据表应设置deleted_at字段。模型内引用SoftDeletes trait,并设置deleted_at字段到$dates属性上。
1 2 3 4 5 6 7 8 | <?php
namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Flight extends Model
{ use SoftDeletes;
protected $dates = ['deleted_at'];
}
|
登录后复制
设置了软删除的模型,在delete方法会设置deleted_at为当前日期和时间。查询软删除的模型会自动排除被软删除的模型。
1 2 3 4 | if ( $flight ->trashed()) {
->where('account_id', 1) ->get(); $flights = App\Flight::onlyTrashed()
->where('airline_id', 1) ->get(); $flight ->restore();
->where('airline_id', 1) ->restore();
|
登录后复制
软删除模型使用强制删除:
查询作用域:
给模型添加查询约束。分全局和本地两种:
全局--每个查询都自动加条件约束;
本地--根据需要调用本地约束。
全局作用域:
首先需实现scope接口类.
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php
namespace App\Scopes; use Illuminate\Database\Eloquent\Scope; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Builder; class AgeScope implements Scope
{
public function apply(Builder $builder , Model $model )
{ return $builder ->where('age', '>', 200);
}
}
|
登录后复制
如果全局作用域要将字段添加到查询的 select 语句中,则应该使用 addSelect
方法而不是 select,以免替换查询的现有select。
应用全局作用域:
在模型的boot方法使用addGlobalScope方法。
1 2 3 4 5 6 7 8 9 10 11 12 | <?php
namespace App; use App\Scopes\AgeScope; use Illuminate\Database\Eloquent\Model; class User extends Model
{
protected static function boot()
{
parent::boot(); static ::addGlobalScope( new AgeScope);
}
}
|
登录后复制
也可以使用闭包定义全局作用域,不必单独定义一个类:
1 2 3 4 5 6 7 8 9 10 11 12 13 | class User extends Model
{
protected static function boot()
{
parent::boot();
static ::addGlobalScope('age', function (Builder $builder ) {
$builder ->where('age', '>', 200);
});
}
}
|
登录后复制
删除全局作用域:
1 2 3 4 | User::withoutGlobalScope(AgeScope:: class )->get();
FirstScope:: class , SecondScope:: class ])->get();
|
登录后复制
本地作用域:
定义通用的约束在需要时使用。定义方法:在模型内定义scope前缀的方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php
namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model
{
public function scopePopular( $query )
{ return $query ->where('votes', '>', 100);
}
public function scopeActive( $query )
{ return $query ->where('active', 1);
}
}
|
登录后复制
使用方法:
1 | $users = App\User::popular()->active()->orderBy('created_at')->get();
|
登录后复制
动态作用域:
1 2 3 4 5 6 7 8 9 | class User extends Model
{
public function scopeOfType( $query , $type )
{ return $query ->where('type', $type );
}
}
|
登录后复制
模型事件:
retrieved
--查询触发
creating
、created--创建触发
updating
、updated--更新触发
saving
、saved--创建、更新触发
deleting
、deleted--删除触发
restoring
、restored--恢复触发
事件指派相应的监控器:
1 2 3 4 5 6 7 8 9 10 11 12 | <?php
namespace App; use App\Events\UserSaved; use App\Events\UserDeleted;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable
{ use Notifiable;
protected $dispatchesEvents = [ 'saved' => UserSaved:: class ,
'deleted' => UserDeleted:: class ,
}
|
登录后复制
也可所有监听放在一个观察器类中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php
namespace App\Observers; use App\User; class UserObserver
{
public function created(User $user )
{
* 监听用户删除事件。
*
* @param User $user
* @ return void */
public function deleting(User $user )
{
}
|
登录后复制
注册观察器:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php
namespace App\Providers; use App\User; use App\Observers\UserObserver;
use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider
{
public function boot()
{
User::observe(UserObserver:: class );
}
}
|
登录后复制
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
Laravel 开发支付宝支付与提现转账的方法
以上是Laravel的Eloquent 模型的介绍的详细内容。更多信息请关注PHP中文网其他相关文章!