Table of Contents
Eloquent model
The model default data table uses the id field as the primary key, and it is an increasing integer type. These can be customized:
Home Backend Development PHP Tutorial Introduction to Laravel's Eloquent model

Introduction to Laravel's Eloquent model

Jul 04, 2018 pm 03:31 PM

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';
}
Copy after login
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;    //主键非自增型}
Copy after login

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;
}
Copy after login

$dateFormat attribute can customize the time cutoff format stored in the data table:

class Flight extends Model
{    /**
     * 模型的日期字段的存储格式     */
    protected $dateFormat = 'U';
}
Copy after login

Customized time cutoff field name:

<?phpclass Flight extends Model
{    const CREATED_AT = &#39;creation_date&#39;;    const UPDATED_AT = &#39;last_update&#39;;
}
Copy after login

Customized database connection:

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

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();             //有条件地查询数据
Copy after login
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) {        //    }
});
Copy after login

Or use the cursor method cursor to greatly reduce memory usage:

foreach (Flight::where(&#39;foo&#39;, &#39;bar&#39;)->cursor() as $flight) {    //}
Copy after login

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();
Copy after login
Aggregation query:

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

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]); //设置条件后再批量更新
Copy after login

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;];
}
Copy after login

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方法
Copy after login
// 通过 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]
);
Copy after login

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();
Copy after login

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;]; 
}
Copy after login

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();
Copy after login

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);
    }
}
Copy after login

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);
    }
}
Copy after login

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);
        });
    }
}
Copy after login

Delete the global scope:

User::withoutGlobalScope(AgeScope::class)->get();  //删除指定的作用域

// 删除所有的全局作用域User::withoutGlobalScopes()->get();// 删除一些全局作用域User::withoutGlobalScopes([
    FirstScope::class, SecondScope::class])->get();
Copy after login

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);
    }
}
Copy after login

使用方法:

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

动态作用域:

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();
Copy after login

模型事件:

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监控器    ];
}
Copy after login

也可所有监听放在一个观察器类中:

<?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)
    {        //    }
}
Copy after login

注册观察器:

<?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);
    }
}
Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles