Laravel framework-detailed explanation of the basic parts of EloquentORM

黄舟
Release: 2023-03-06 19:34:01
Original
1674 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template