Home  >  Article  >  Backend Development  >  Introduction to Laravel's Eloquent model

Introduction to Laravel's Eloquent model

不言
不言Original
2018-07-04 15:31:252030browse

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.

Eloquent model

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:

The model default data table uses the id field as the primary key, and it is an increasing integer type. These can be customized:

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 = &#39;creation_date&#39;;    const UPDATED_AT = &#39;last_update&#39;;
}

Customized database connection:

class Flight extends Model
{    /**
     * 此模型的连接名称。     */
    protected $connection = &#39;connection-name&#39;;
}

Model query:

use App\Flight;$flights = App\Flight::all();   //查询所有数据
foreach ($flights as $flight) {    echo $flight->name;
}$flights = App\Flight::where(&#39;active&#39;, 1)               
->orderBy(&#39;name&#39;, &#39;desc&#39;)               
->take(10)               
->get();             //有条件地查询数据
The all and get methods return

Illuminate\Database\Eloquent\Collection

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(&#39;foo&#39;, &#39;bar&#39;)->cursor() as $flight) {    //}

Query Single piece of data:

// 通过主键取回一个模型...$flight = App\Flight::find(1);
// 取回符合查询限制的第一个模型 ...
$flight = App\Flight::where(&#39;active&#39;, 1)->first();//如果找不到模型则抛出异常
//Illuminate\Database\Eloquent\ModelNotFoundException
//自动返回 HTTP 404 响应给用户
$model = App\Flight::where(&#39;legs&#39;, &#39;>&#39;, 100)->firstOrFail();
Aggregation query:

$count = App\Flight::where(&#39;active&#39;, 1)->count();$max = App\Flight::where(&#39;active&#39;, 1)->max(&#39;price&#39;);

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 = &#39;New Flight Name&#39;;$flight->save(); //查询一次后再更新
App\Flight::where(&#39;active&#39;, 1)          
->where(&#39;destination&#39;, &#39;San Diego&#39;)          
->update([&#39;delayed&#39; => 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 = [&#39;name&#39;];
}class Flight extends Model
{    /**
     * 不可被批量赋值的属性。可定义为空数组,表示所有属性都可以赋值。
     * @var array     */
    protected $guarded = [&#39;price&#39;];
}

Method of inserting data:

$flight = App\Flight::create([&#39;name&#39; => &#39;Flight 10&#39;]); //添加新记录并返回已保存的模型实例
$flight->fill([&#39;name&#39; => &#39;Flight 22&#39;]); //已有实例模型可使用fill方法
// 通过 name 属性检索航班,当结果不存在时创建它...
$flight = App\Flight::firstOrCreate([&#39;name&#39; => &#39;Flight 10&#39;]);// 通过 name 属性检索航班,当结果不存在的时候用 name 属性和 delayed 属性去创建它$flight = App\Flight::firstOrCreate(
    [&#39;name&#39; => &#39;Flight 10&#39;], [&#39;delayed&#39; => 1]
);// 通过 name 属性检索航班,当结果不存在时实例化...
$flight = App\Flight::firstOrNew([&#39;name&#39; => &#39;Flight 10&#39;]);// 通过 name 属性检索航班,当结果不存在的时候用 name 属性和 delayed 属性实例化$flight = App\Flight::firstOrNew(
    [&#39;name&#39; => &#39;Flight 10&#39;], [&#39;delayed&#39; => 1]
);// 如果有从奥克兰飞往圣地亚哥的航班,将价格设为 99 美元
// 如果不存在匹配的模型就创建一个
$flight = App\Flight::updateOrCreate(
    [&#39;departure&#39; => &#39;Oakland&#39;, &#39;destination&#39; => &#39;San Diego&#39;],
    [&#39;price&#39; => 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(&#39;active&#39;, 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 = [&#39;deleted_at&#39;]; 
}

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(&#39;account_id&#39;, 1)                ->get();$flights = App\Flight::onlyTrashed()  //只查询软删除的数据
                ->where(&#39;airline_id&#39;, 1)                ->get();$flight->restore();  //恢复被软删除的模型App\Flight::withTrashed()   //批量恢复模型,不会触发任何模型事件
        ->where(&#39;airline_id&#39;, 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(&#39;age&#39;, &#39;>&#39;, 200);
    }
}

If the global scope wants to add fields to the select statement of the query, you should use

addSelect

method instead of

select to avoid replacing the query's existing select. Apply global scope:

Use the addGlobalScope method in the model's boot method.

<?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(&#39;age&#39;, function(Builder $builder) {            
        $builder->where(&#39;age&#39;, &#39;>&#39;, 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(&#39;votes&#39;, &#39;>&#39;, 100);
    }    /**
     * 限制查询只包括活跃的用户。
     *
     * @return \Illuminate\Database\Eloquent\Builder     */
    public function scopeActive($query)
    {        return $query->where(&#39;active&#39;, 1);
    }
}

使用方法:

$users = App\User::popular()->active()->orderBy(&#39;created_at&#39;)->get();

动态作用域:

class User extends Model
{    /**
     * 限制查询只包括指定类型的用户。
     *
     * @return \Illuminate\Database\Eloquent\Builder     */
    public function scopeOfType($query, $type)
    {        return $query->where(&#39;type&#39;, $type);
    }
}//调用作用域时传参$users = App\User::ofType(&#39;admin&#39;)->get();

模型事件:

retrieved --查询触发

creatingcreated--创建触发

updatingupdated--更新触发

savingsaved--创建、更新触发

deletingdeleted--删除触发

restoringrestored--恢复触发

事件指派相应的监控器:

<?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 = [        &#39;saved&#39; => UserSaved::class,   //触发saved事件,调用UserSaved监控器
        &#39;deleted&#39; => 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中文网!

相关推荐:

 Laravel 开发支付宝支付与提现转账的方法

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn