Eloquent ORM overview, model definition and basic query details

Source: Internet
Author: User
Tags dateformat table name

1. Intro

Before entering this section formally, let's take a look at what ORM is.

ORM, the Object-relational Mapping (Object relational mapping), is a mapping between relational databases and business entity objects, so that we don't have to deal with complex SQL statements when we're working with specific business objects. Simply manipulate the properties and methods of the object.

One of the most common implementations of ORM is that ActiveRecord and Datamapper,activerecord are particularly popular and can be seen in many frameworks. The difference between the two is that the ActiveRecord model corresponds to the data table one by one, and the Datamapper model is completely separated from the data table.

Laravel in the eloquent ORM is also used ActiveRecord implementation, each eloquent model class corresponding to a table in the database, we call the model class of the corresponding method to change the database additions and deletions to check.

2. Define the Model

2.1 Creating a Model

We use the artisan command Make:model generate the model class, the model class is in the app directory by default, and we can specify the build directory at the time of creation:

PHP Artisan Make:model Models/post

This generates a models directory under the app directory and generates a post model class in the models directory. All model classes in Laravel inherit from Illuminate\database\eloquent\model classes.

2.2 Specifying the table name

If you do not specify it manually, the default post corresponds to the datasheet posts, and so on. You can also customize the table name by setting the $table property:

Public $table = ' posts ';

2.3 Specifying a PRIMARY key

Eloquent the default datasheet primary key is ID, and of course you can customize the primary key by setting the $primarykey property:

Public $primaryKey = ' id ';

2.4 Time stamp settings

By default, the eloquent model class automatically manages timestamp columns Create_at and UPDATE_AT (if the two columns are set when the migration is defined), you can set the $timestamps property to False if you want to cancel automatic management:

Public $timestamps = false;

Also, if you want to format the timestamp, you can use the $dateformat property, which determines what format the date time is stored in the database and in what format it is displayed:

Set date time format to UNIX timestamp
protected $dateFormat = ' U ';

For more information on date-time formatting, refer to the Format section of the PHP official function date.

3. Query data

3.1 Getting multiple models

We can use the all method on the eloquent model to get all the model instances, for example, we get all the articles by using the following methods:

<?php

namespace App\http\controllers;

Use Illuminate\http\request;

Use app\http\requests;
Use App\http\controllers\controller;

Use App\models\post;

Class TestController extends Controller
{

/**
* Display A listing of the resource.
*
* @return Response
*/
Public Function Index ()
{

Get multiple eloquent models
$posts = Post::all ();
DD ($posts);

}
}

The visible output is a collection of model arrays, with each $items element corresponding to a post model instance.

Also, it is necessary to understand that each eloquent model itself is a query builder, all of which we can invoke on all query builders, except that the first method call uses a static method call:

$posts = post::where (' id ', ' < ', 3)->orderby (' id ', ' desc ')->take (1)->get ();
DD ($posts);

You may have noticed that the model query return result is an instance of illuminate\database\eloquent\collection that implements the Arrayaccess interface, so we can access the instance like an array, and in addition, The collection class also provides a number of other useful methods for processing query results, as detailed in the source code.

Since the eloquent model is a query builder, it is natural to support block blocks for data acquisition:

Post::chunk (2,function ($posts) {
foreach ($posts as $post) {
echo $post->title. ' <br> ';
}
});

The output results are as follows:

Test 1
Test 2
Test 3

3.2 Getting a single model

You can use the Query builder method to get a single model instance:

$post = post::where (' id ', 1)->first ();
DD ($post);

Of course, you can also use the shortcut method provided by the eloquent model class find:

$post = Post::find (1);

If you do not find the corresponding table record, output null, if we want to capture the query result is empty exception and processing, such as jump to 404 pages, you can use the Findorfail or Firstorfail method, if the table records exist, both return to the first record of the acquisition, Otherwise, the illuminate\database\eloquent\modelnotfoundexception exception is thrown.

3.3 Aggregate function Query

If you want to query the results of the count, statistics, maximum/minimum, average, and other aggregation operations, you can use the Query builder of the corresponding method, we query the total number of articles:

$count = post::where (' id ', ' > ', 0)->count ();
Echo $count;
The output is 3, or we want to get the maximum number of readings for the article:

$views = post::where (' id ', ' > ', 0)->max (' views ');
Echo $views;
The output result is 800.

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.