Laravel framework-EloquentORM basics

Source: Internet
Author: User
When Eloquent [el ə kw ə nt] is used, the method of the database query constructor is also used for the model class. the DB: table ('Table name') is omitted '). Eloquent ['eləkwənt]The database query constructor method is also used for model classes. DB::table('Table name.

In the model, use the protected member variable $ table to specify the bound table name.

 

EloquentAssume that each table has a primary key named id.$primaryKeyThe member variable overwrites the field name. In addition,EloquentAssume that the primary key field is an auto-increment integer. if you want to use a non-auto-incrementing primary key or a non-numeric primary key, you must specifypublicAttribute$incrementingIsfalse.
By default,EloquentExpected table existscreated_atAndupdated_atTwo Fields. the field type istimestampIf you do not want these two fields, set$timestampsIsfalse

  

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

Query

Basic query operation #
The all method is used to return all results in the model table.

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

You can also usegetMethod to add constraints for query results

$flights = App\Flight::where('active', 1)     ->orderBy('name', 'desc')     ->take(10)     ->get();

We can see that the method of the query constructor can also be used for the model class.

In eloquent ORM,getAndallMethod to query multiple result sets. their return value isIlluminate\Database\Eloquent\CollectionObject. this object provides multiple methods to operate the result set.

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

There are many methods for this object. only a small part is listed here. For more methods, refer to the API documentation Collection and instructions. Chunk is also used for processing a large number of results in segments.

Flight::chunk(200, function ($flights) {    foreach ($flights as $flight) {        //    }});
Query a single result

UsefindAndfirstMethod to query a single result. a single model instance is returned.

// Query the model using the primary key... $ flight = App \ Flight: find (1); // use constraints... $ flight = App \ Flight: where ('activity', 1)-> first ();

UsefindMethod can also return multiple resultsCollectionReturns an object with multiple primary keys.

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

You can usefindOrFailOrfirstOrFailMethod, the two methods will throwIlluminate\Database\Eloquent\ModelNotFoundExceptionException

$model = App\Flight::findOrFail(1);$model = App\Flight::where('legs', '>', 100)->firstOrFail();

If this exception is not captured, laravel will automatically return a 404 response to the user. Therefore, if you want to return 404 if you cannot find it, you can directly use this method to return

Route::get('/api/flights/{id}', function ($id) {    return App\Flight::findOrFail($id);});
Query aggregate function results

Like the query method of the query constructor, clustering functions can be used to return results. Common examples include max, min, avg, sum, and count.

$count = App\Flight::where('active', 1)->count();$max = App\Flight::where('active', 1)->max('price');
Paging query

Paginate functions can be directly used for paging queries.

LengthAwarePaginator paginate(     int $perPage = null,     array $columns = array('*'),     string $pageName = 'page',     int|null $page = null)

Parameter description
Parameter type description
PerPage int number per page
Column name queried by columns array
PageName string page number parameter name
Page int current page number

The returned value isLengthAwarePaginatorObject.

$limit = 20;$page = 1;return Enterprise::paginate($limit, ['*'], 'page', $page);
Insert

Basic insert operation #

To insert new data, you only need to create a new model instance, set the model attributes, and call the save method.

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

When the save method is called, the timestamp is automatically set for the created_at and updated_at fields.

Batch value insertion #

UsecreateYou can perform batch insert operations to assign values to model attributes. this method returns the newly inserted model.createYou must specifyfillableAndguardedAttribute, used to prevent illegal attribute assignment (for example, to prevent user inputis_adminAttribute is mistakenly entered into the data table ).

Specify$fillableThe purpose of the attribute is that the specified field cancreateOther fields will be filtered out, similar to the whitelist, and$guardedOn the contrary, it is similar to a blacklist.

protected $fillable = ['name'];// ORprotected $guarded = ['price'];

After you execute the create operation, only fields other than 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.

firstOrCreateThe method is used to query records using the given column value pairs. If no record is found, a new record is inserted.fristOrNewAndfirstOrCreateSimilarly, the difference is that if it does not exist, it will return a new model object. However, this model is not persistent and needs to be manually called to save the method to the database.

// Use the property to retrieve the flight. if it does not exist, the flight is created... $ flight = App \ Flight: firstOrCreate (['name' => 'Flight 10']); // use the property to retrieve Flight. if it does not exist, create a model instance... $ flight = App \ Flight: firstOrNew (['name' => 'Flight 10']);
Update

Basic update operation #

The method save can be used not only to insert new data, but also to update data. you only need to use the model method to query the data to be updated and set the model attribute to a new value, then save and update the updated_at field.

$flight = App\Flight::find(1);$flight->name = 'New Flight Name';$flight->save();

You can also use the update method to update multiple results.

App\Flight::where('active', 1)    ->where('destination', 'San Diego')    ->update(['delayed' => 1]);
Delete

Basic delete operation #
UsedeleteMethod to delete a model

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

The above method needs to query the model object before deleting it. you can also directly use the primary key to delete the model without querying it. use the destroy method.

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

Delete with constraints and return the number of deleted rows

$deletedRows = App\Flight::where('active', 0)->delete();
Soft delete

Soft delete adds the deleted_at field to the table. when a record is deleted, the record is not deleted, but the timestamp of the field is set. the Eloquent model shields the data that has already been set for this field.

To enable soft delete, you can reference the Trait of Illuminate \ Database \ Eloquent \ SoftDeletes in the model and add the deleted_at field to the dates attribute.

   

You can use the trashed method to determine whether a model has been deleted.

if ($flight->trashed()) {    //}

Querying soft-deleted models #

Model containing soft deletion #

If the model is deleted, the normal query will not query the result. you can use the withTrashed method to forcibly return the soft deletion result.

$ Flights = App \ Flight: withTrashed ()-> where ('account _ id', 1)-> get (); // You can also use $ flight-> history ()-> withTrashed ()-> get ();

Queries only soft-deleted models #

$flights = App\Flight::onlyTrashed()      ->where('airline_id', 1)      ->get();

Restore the soft-deleted model #

Call the restore method to restore a soft-deleted model instance.

$flight->restore();

You can also use

App \ Flight: withTrashed ()-> where ('Airline _ id', 1)-> restore (); // $ flight-> history () can also be used in association operations () -> restore ();

Force delete (persistent delete )#

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

After the preceding operations, the data is actually deleted.

The above is the detailed description of the basic part of the Laravel framework-EloquentORM. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.