Table of Contents
Query
is also used to query a single result.
FunctionResult" >Query aggregationFunctionResult
Paging query
Insertion
Update
删除
软删除" >软删除
Home Backend Development PHP Tutorial Laravel framework-detailed explanation of the basic parts of EloquentORM

Laravel framework-detailed explanation of the basic parts of EloquentORM

Mar 21, 2017 am 09:22 AM

Eloquent ['eləkwənt], the database query constructor method is also used for the model class, but DB::table('table name' is omitted in use )part.

Use the protected member variable $table in the model to specify the bound table name.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;class Flight extends Model{    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = &#39;my_flights&#39;;
}
Copy after login

Eloquent Assume that each table has a primary key named id, which can be overridden by the $primaryKey member variable. In addition, Eloquent Assume that the primary key field is an auto-increasing integer. If you want to use a non-auto-increasing primary key or a non-numeric primary key, you must specify the public attribute $incrementing in the model as false.
By default, Eloquent expects two fields created_at and updated_at to exist in the table, with the field type being timestamp, if not If you want these two fields, set $timestamps to false

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;class Flight extends Model{    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;    /**
     * The storage format of the model&#39;s date columns.
     *
     * @var string
     */
    protected $dateFormat = &#39;U&#39;;
}
Copy after login

Use protected $connection = 'connection-name' to specify the database connection used by the model.

Query

Basic query operations
#Method all is used to return all results in the model table

$flights = Flight::all();foreach ($flights as $flight) {    echo $flight->name;
}
Copy after login

You can also use the get method to Add constraints to query results

$flights = App\Flight::where(&#39;active&#39;, 1)
     ->orderBy(&#39;name&#39;, &#39;desc&#39;)
     ->take(10)
     ->get();
Copy after login

You can see that the query constructor method can also be used on model classes

In eloquent ORM, get and all The method queries multiple result sets, and their return value is an Illuminate\Database\Eloquent\Collection object, which provides a variety of methods for operating on the result set

public function find($key, $default = null);
public function contains($key, $value = null);
public function modelKeys();
public function diff($items)...
Copy after login

This object has many methods, only a small part is listed here. For more methods, please refer to the API document Collection and usage documentation. For segmented processing of a large number of results, the chunk method

Flight::chunk(200, function ($flights) {
    foreach ($flights as $flight) {        //
    }
});
Copy after login

is also used to query a single result.

Use the find and first methods to query a single result and return It is a single model instance

// 通过主键查询模型...$flight = App\Flight::find(1);

// 使用约束...$flight = App\Flight::where(&#39;active&#39;, 1)->first();
Copy after login

Using the find method can also return multiple results, in the form of a Collection object, and the parameters are multiple primary keys

$flights = App\Flight::find([1, 2, 3]);
Copy after login

If you can't find the result, you can use the findOrFail or firstOrFail method. These two methods will throw Illuminate\Database when you can't find the result. \Eloquent\ModelNotFound<a href="http://www.php.cn/wiki/265.html" target="_blank">Exception</a>Exception

$model = App\Flight::findOrFail(1);$model = App\Flight::where(&#39;legs&#39;, &#39;>&#39;, 100)->firstOrFail();
Copy after login

If this exception is not caught, laravel will automatically return a 404 response result to the user, so if you want to return it when it cannot be found 404, can be returned directly using this method

Route::get(&#39;/api/flights/{id}&#39;, function ($id) {
    return App\Flight::findOrFail($id);
});
Copy after login

Query aggregationFunctionResult

Like the query constructor query method, you can use aggregate functions to return results, common For example, max, min, avg, sum, count, etc.

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

Paging query

Paging query can directly use the paginate function

LengthAwarePaginator paginate( 
    int $perPage = null, 
    array $columns = array(&#39;*&#39;), 
    string $pageName = &#39;page&#39;, 
    int|null $page = null)
Copy after login

Parameter description
Parameter Type Description
perPage int Number displayed per page
columns array Query column name
pageName string Page number parameter name
page int Current page number

The return value is the LengthAwarePaginator object.

$limit = 20;$page = 1;return Enterprise::paginate($limit, [&#39;*&#39;], &#39;page&#39;, $page);
Copy after login

Insertion

Basic insertion operation

#To insert new data, you only need to create a new model instance, then set the model properties, and finally call the save method

$flight = new Flight;$flight->name = $request->name;$flight->save();
Copy after login

When calling the save method, timestamps will be automatically set for the created_at and updated_at fields. There is no need to manually specify

Batch assignment insertion

#Use createThe method can perform batch insertion operations of assigning values ​​to model attributes. This method will return the newly inserted model. Before executing the create method, you need to specify fillable and The guarded attribute is used to prevent illegal attribute assignment (for example, to prevent the is_admin attribute passed in by the user from being mistakenly entered into the data table).

The purpose of specifying the $fillable attribute is that the field specified by this attribute can be inserted through the create method, and other fields will be filtered out, similar to a whitelist, and $guarded is the opposite, similar to a blacklist.

protected $fillable = [&#39;name&#39;];// ORprotected $guarded = [&#39;price&#39;];
Copy after login

When performing the create operation, only fields outside the whitelist or blacklist can be updated.

$flight = App\Flight::create([&#39;name&#39; => &#39;Flight 10&#39;]);
Copy after login

In addition to the create method, there are two other methods that can use firstOrNew and firstOrCreate.

firstOrCreate method is used to use the given column value pair to query the record , and insert a new one if it cannot be found. fristOrNew is similar to firstOrCreate, the difference is that if it does not exist, it will return a new model object, but the model is not persisted, and you need to manually call the save method to persist it to database.

// 使用属性检索flight,如果不存在则创建...$flight = App\Flight::firstOrCreate([&#39;name&#39; => &#39;Flight 10&#39;]);

// 使用属性检索flight,如果不存在则创建一个模型实例...$flight = App\Flight::firstOrNew([&#39;name&#39; => &#39;Flight 10&#39;]);
Copy after login

Update

Basic update operation

#The save method can not only be used to insert new data, but also to update data. You only need to use the model method to query first Extract the data to be updated, set the model attributes to new values, and then save to update. The updated_at field will be automatically updated.

$flight = App\Flight::find(1);$flight->name = &#39;New Flight Name&#39;;$flight->save();
Copy after login

也可使用update方法对多个结果进行更新

App\Flight::where(&#39;active&#39;, 1)
    ->where(&#39;destination&#39;, &#39;San Diego&#39;)
    ->update([&#39;delayed&#39; => 1]);
Copy after login

删除

基本删除操作#
使用delete方法删除模型

$flight = App\Flight::find(1);$flight->delete();
Copy after login

上述方法需要先查询出模型对象,然后再删除,也可以直接使用主键删除模型而不查询,使用destroy方法

App\Flight::destroy(1);App\Flight::destroy([1, 2, 3]);App\Flight::destroy(1, 2, 3);
Copy after login

使用约束条件删除,返回删除的行数

$deletedRows = App\Flight::where(&#39;active&#39;, 0)->delete();
Copy after login

软删除

软删除是在表中增加deleted_at字段,当删除记录的时候不会真实删除记录,而是设置该字段的时间戳,由Eloquent模型屏蔽已经设置该字段的数据。

要启用软删除,可以在模型中引用Illuminate\Database\Eloquent\SoftDeletes这个Trait,并且在dates属性中增加deleted_at字段。

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;class Flight extends Model{
    use SoftDeletes;    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = [&#39;deleted_at&#39;];
}
Copy after login

要判断一个模型是否被软删除了的话,可以使用trashed方法

if ($flight->trashed()) {    //}
Copy after login

查询软删除的模型#

包含软删除的模型#

如果模型被软删除了,普通查询是不会查询到该结果的,可以使用withTrashed方法强制返回软删除的结果

$flights = App\Flight::withTrashed()
      ->where(&#39;account_id&#39;, 1)
      ->get();// 关联操作中也可以使用
$flight->history()->withTrashed()->get();
Copy after login

只查询软删除的模型#

$flights = App\Flight::onlyTrashed()
      ->where(&#39;airline_id&#39;, 1)
      ->get();
Copy after login

还原软删除的模型#

查询到软删除的模型实例之后,调用restore方法还原

$flight->restore();
Copy after login

也可以在查询中使用

App\Flight::withTrashed()
    ->where(&#39;airline_id&#39;, 1)
    ->restore();// 关联操作中也可以使用
$flight->history()->restore();
Copy after login

强制删除(持久化删除)#

// Force deleting a single model instance...$flight->forceDelete();
// Force deleting all related models...$flight->history()->forceDelete();
Copy after login

上述操作后,数据会被真实删除。

The above is the detailed content of Laravel framework-detailed explanation of the basic parts of EloquentORM. 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
Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Apr 18, 2025 am 09:24 AM

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

How to learn Laravel How to learn Laravel for free How to learn Laravel How to learn Laravel for free Apr 18, 2025 pm 12:51 PM

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

Laravel user login function Laravel user login function Apr 18, 2025 pm 12:48 PM

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

How to view the version number of laravel? How to view the version number of laravel How to view the version number of laravel? How to view the version number of laravel Apr 18, 2025 pm 01:00 PM

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

What versions of laravel are there? How to choose the version of laravel for beginners What versions of laravel are there? How to choose the version of laravel for beginners Apr 18, 2025 pm 01:03 PM

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

The difference between laravel and thinkphp The difference between laravel and thinkphp Apr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

See all articles