


Laravel framework-detailed explanation of the basic parts of EloquentORM
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 = 'my_flights'; }
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's date columns. * * @var string */ protected $dateFormat = 'U'; }
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; }
You can also use the get
method to Add constraints to query results
$flights = App\Flight::where('active', 1) ->orderBy('name', 'desc') ->take(10) ->get();
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)...
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) { // } });
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('active', 1)->first();
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]);
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('legs', '>', 100)->firstOrFail();
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('/api/flights/{id}', function ($id) { return App\Flight::findOrFail($id); });
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('active', 1)->count();$max = App\Flight::where('active', 1)->max('price');
Paging query
Paging query can directly use the paginate function
LengthAwarePaginator paginate( int $perPage = null, array $columns = array('*'), string $pageName = 'page', int|null $page = null)
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, ['*'], 'page', $page);
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();
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 create
The 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 = ['name'];// ORprotected $guarded = ['price'];
When performing the create operation, only fields outside the whitelist or blacklist can be updated.
$flight = App\Flight::create(['name' => 'Flight 10']);
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(['name' => 'Flight 10']); // 使用属性检索flight,如果不存在则创建一个模型实例...$flight = App\Flight::firstOrNew(['name' => 'Flight 10']);
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 = 'New Flight Name';$flight->save();
也可使用update方法对多个结果进行更新
App\Flight::where('active', 1) ->where('destination', 'San Diego') ->update(['delayed' => 1]);
删除
基本删除操作#
使用delete
方法删除模型
$flight = App\Flight::find(1);$flight->delete();
上述方法需要先查询出模型对象,然后再删除,也可以直接使用主键删除模型而不查询,使用destroy方法
App\Flight::destroy(1);App\Flight::destroy([1, 2, 3]);App\Flight::destroy(1, 2, 3);
使用约束条件删除,返回删除的行数
$deletedRows = App\Flight::where('active', 0)->delete();
软删除
软删除是在表中增加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 = ['deleted_at']; }
要判断一个模型是否被软删除了的话,可以使用trashed方法
if ($flight->trashed()) { //}
查询软删除的模型#
包含软删除的模型#
如果模型被软删除了,普通查询是不会查询到该结果的,可以使用withTrashed方法强制返回软删除的结果
$flights = App\Flight::withTrashed() ->where('account_id', 1) ->get();// 关联操作中也可以使用 $flight->history()->withTrashed()->get();
只查询软删除的模型#
$flights = App\Flight::onlyTrashed() ->where('airline_id', 1) ->get();
还原软删除的模型#
查询到软删除的模型实例之后,调用restore方法还原
$flight->restore();
也可以在查询中使用
App\Flight::withTrashed() ->where('airline_id', 1) ->restore();// 关联操作中也可以使用 $flight->history()->restore();
强制删除(持久化删除)#
// Force deleting a single model instance...$flight->forceDelete(); // Force deleting all related models...$flight->history()->forceDelete();
上述操作后,数据会被真实删除。
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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.

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.

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 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

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.

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.

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.

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.
