Home >Backend Development >PHP Tutorial >Introduction to Laravel's Eloquent model
This article mainly introduces the introduction of Laravel's Eloquent model. It has certain reference value. Now I share it with everyone. Friends in need can refer to it.
Default Inherit the use Illuminate\Database\Eloquent\Model class.
#Data table name and model name convention:
The database table names are generally named using the "snake nomenclature". Snake nomenclature requires words to be lowercase, words to be connected by _underscores, and names to be plural.
##The corresponding model name is named using the "Pascal method" , that is, the first letter of each word is capitalized.
If the above agreement is not followed, the corresponding data table needs to be specified: class Flight extends Model
{ /**
* 与模型关联的数据表
*
* @var string */
protected $table = 'myflights';
}
Primary key:
class Flight extends Model { /** * 与模型关联的数据表 */ protected $table = 'my_flights'; protected $primaryKey='mid'; //自定义主键字段 protected $keyType = 'string'; //自定义主键类型为字串 public $incrementing = false; //主键非自增型}Time cutoff:
The model has two fields, created_at and updated_at by default. You can set $timestamps without the two fields:
class Flight extends Model { /** * 该模型是否被自动维护时间戳 */ public $timestamps = false; }
$dateFormat attribute can customize the time cutoff format stored in the data table:
class Flight extends Model { /** * 模型的日期字段的存储格式 */ protected $dateFormat = 'U'; }
Customized time cutoff field name:
<?phpclass Flight extends Model { const CREATED_AT = 'creation_date'; const UPDATED_AT = 'last_update'; }Customized database connection:
class Flight extends Model
{ /**
* 此模型的连接名称。 */
protected $connection = 'connection-name';
}
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(); //有条件地查询数据
The all and get methods return
instances. If you query large batches of data, you can use chunks to save memory:
Flight::chunk(200, function ($flights) { foreach ($flights as $flight) { // } });
Or use the cursor method cursor to greatly reduce memory usage:
foreach (Flight::where('foo', 'bar')->cursor() as $flight) { //}Query Single piece of data:
// 通过主键取回一个模型...$flight = App\Flight::find(1);
// 取回符合查询限制的第一个模型 ...
$flight = App\Flight::where('active', 1)->first();//如果找不到模型则抛出异常
//Illuminate\Database\Eloquent\ModelNotFoundException
//自动返回 HTTP 404 响应给用户
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
Aggregation query:
$count = App\Flight::where('active', 1)->count();$max = App\Flight::where('active', 1)->max('price');Data update:
save method: Need to retrieve once first, and then set to update Then execute the save method for the attribute, and updated_at will be automatically updated at the same time.
Update method: Set the where condition and pass the update field into the update method as a key-value pair. The update does not trigger saved and updated model events.
$flight = App\Flight::find(1); $flight->name = 'New Flight Name';$flight->save(); //查询一次后再更新 App\Flight::where('active', 1) ->where('destination', 'San Diego') ->update(['delayed' => 1]); //设置条件后再批量更新Insert data:
To use the model to create data, you need to set the $fillable or $guarded attribute first. You can only choose one of the two attributes.
class Flight extends Model { /** * 可以被批量赋值的属性。 * @var array */ protected $fillable = ['name']; }class Flight extends Model { /** * 不可被批量赋值的属性。可定义为空数组,表示所有属性都可以赋值。 * @var array */ protected $guarded = ['price']; }
Method of inserting data:
$flight = App\Flight::create(['name' => 'Flight 10']); //添加新记录并返回已保存的模型实例 $flight->fill(['name' => 'Flight 22']); //已有实例模型可使用fill方法
// 通过 name 属性检索航班,当结果不存在时创建它... $flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);// 通过 name 属性检索航班,当结果不存在的时候用 name 属性和 delayed 属性去创建它$flight = App\Flight::firstOrCreate( ['name' => 'Flight 10'], ['delayed' => 1] );// 通过 name 属性检索航班,当结果不存在时实例化... $flight = App\Flight::firstOrNew(['name' => 'Flight 10']);// 通过 name 属性检索航班,当结果不存在的时候用 name 属性和 delayed 属性实例化$flight = App\Flight::firstOrNew( ['name' => 'Flight 10'], ['delayed' => 1] );// 如果有从奥克兰飞往圣地亚哥的航班,将价格设为 99 美元 // 如果不存在匹配的模型就创建一个 $flight = App\Flight::updateOrCreate( ['departure' => 'Oakland', 'destination' => 'San Diego'], ['price' => 99] );
firstOrCreate: If the data cannot be found, create a record based on the first parameter and second parameter record and return the saved model;
firstOrNew: If the data cannot be found, a new model will be created based on the first and second parameter records, but the data will not be saved. You need to save it manually to save the data;
updateOrCreate: Based on the first parameter Use the condition to update the second parameter data. If the data does not exist, merge the two parameters to create a record and return the saved model.
Delete models:
$flight = App\Flight::find(1);$flight->delete(); //通过查询所得的模型实例进行delete方法删除 //通过主键删除一至多条数据:App\Flight::destroy(1); App\Flight::destroy([1, 2, 3]); App\Flight::destroy(1, 2, 3);//通过查询条件批量删除,并返回删除条数 $deletedRows = App\Flight::where('active', 0)->delete();
When deleting in batches, the deleted and deleting model events will not be triggered.
Soft deletion:
The data table should set the deleted_at field. Reference the SoftDeletes trait in the model and set the deleted_at field to the $dates attribute.
<?php namespace App;use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\SoftDeletes;class Flight extends Model { use SoftDeletes; /** * 需要被转换成日期的属性。 * @var array */ protected $dates = ['deleted_at']; }
The soft deletion model is set, and deleted_at is set to the current date and time in the delete method. Querying soft-deleted models will automatically exclude soft-deleted models.
if ($flight->trashed()) { //检查该模型实例是否被软删除}$flights = App\Flight::withTrashed() //能使用查询包含软删除的数据 ->where('account_id', 1) ->get();$flights = App\Flight::onlyTrashed() //只查询软删除的数据 ->where('airline_id', 1) ->get();$flight->restore(); //恢复被软删除的模型App\Flight::withTrashed() //批量恢复模型,不会触发任何模型事件 ->where('airline_id', 1) ->restore();
Soft delete model uses force delete:
$flight->forceDelete();##Query scope:
Add query constraints to the model. There are two types: global and local: global--conditional constraints are automatically added to each query; local--local constraints are called as needed. Global scope: First you need to implement the scope interface class.<?php namespace App\Scopes;use Illuminate\Database\Eloquent\Scope;use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Builder;class AgeScope implements Scope { /** * 将范围应用于给定的 Eloquent 查询生成器 * * @param \Illuminate\Database\Eloquent\Builder $builder * @param \Illuminate\Database\Eloquent\Model $model * @return void */ public function apply(Builder $builder, Model $model) { return $builder->where('age', '>', 200); } }If the global scope wants to add fields to the select statement of the query, you should use
addSelect
method instead ofselect to avoid replacing the query's existing select. Apply global scope:
<?php namespace App;use App\Scopes\AgeScope;use Illuminate\Database\Eloquent\Model;class User extends Model { /** * 模型的「启动」方法 * * @return void */ protected static function boot() { parent::boot(); static::addGlobalScope(new AgeScope); } }You can also use closures to define the global scope without defining a separate class:
class User extends Model { /** * 模型的「启动」方法 * * @return void */ protected static function boot() { parent::boot(); static::addGlobalScope('age', function(Builder $builder) { $builder->where('age', '>', 200); }); } }Delete the global scope:
User::withoutGlobalScope(AgeScope::class)->get(); //删除指定的作用域 // 删除所有的全局作用域User::withoutGlobalScopes()->get();// 删除一些全局作用域User::withoutGlobalScopes([ FirstScope::class, SecondScope::class])->get();Local scope:
定义通用的约束在需要时使用。定义方法:在模型内定义scope前缀的方法。
<?php namespace App;use Illuminate\Database\Eloquent\Model;class User extends Model { /** * 限制查询只包括受欢迎的用户。 * * @return \Illuminate\Database\Eloquent\Builder */ public function scopePopular($query) { return $query->where('votes', '>', 100); } /** * 限制查询只包括活跃的用户。 * * @return \Illuminate\Database\Eloquent\Builder */ public function scopeActive($query) { return $query->where('active', 1); } }
使用方法:
$users = App\User::popular()->active()->orderBy('created_at')->get();
动态作用域:
class User extends Model { /** * 限制查询只包括指定类型的用户。 * * @return \Illuminate\Database\Eloquent\Builder */ public function scopeOfType($query, $type) { return $query->where('type', $type); } }//调用作用域时传参$users = App\User::ofType('admin')->get();
模型事件:
retrieved
--查询触发
creating
、created--创建触发
updating
、updated--更新触发
saving
、saved--创建、更新触发
deleting
、deleted--删除触发
restoring
、restored--恢复触发
事件指派相应的监控器:
<?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; /** * 模型的事件映射。 * * @var array */ protected $dispatchesEvents = [ 'saved' => UserSaved::class, //触发saved事件,调用UserSaved监控器 'deleted' => UserDeleted::class, //触发deleted事件,调用UserDeleted监控器 ]; }
也可所有监听放在一个观察器类中:
<?php namespace App\Observers;use App\User;class UserObserver { /** * 监听用户创建的事件。 * * @param User $user * @return void */ public function created(User $user) { // } /** * 监听用户删除事件。 * * @param User $user * @return void */ public function deleting(User $user) { // } }
注册观察器:
<?php namespace App\Providers;use App\User;use App\Observers\UserObserver; use Illuminate\Support\ServiceProvider;class AppServiceProvider extends ServiceProvider { /** * 运行所有应用. * * @return void */ public function boot() { User::observe(UserObserver::class); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
The above is the detailed content of Introduction to Laravel's Eloquent model. For more information, please follow other related articles on the PHP Chinese website!