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.
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) { // } });
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="//m.sbmmt.com/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); });
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 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);
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']);
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!