Laravel Learning Notes (vi)---operation database--eloquent ORM (Object Relational mapping)

Source: Internet
Author: User
Tags dateformat
Eloquent ORM (Object relational mapping)
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 ';

3. Query data
3.1 Getting multiple models

We can use the all method on the eloquent model to get all model instances
$posts = Post::all ();
What needs to be learned is 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);
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);

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;

Call the Save method of the eloquent model class to create the model and insert the data into the database:

1.2 Inserting data using the Create method

In addition, you can use the Create method to insert data, because the method uses a bulk assignment (Mass assignment), so we need to set the $fillable property or $guarded property in the model class to indicate which properties can be set by this method. which cannot be.

Before we start, let's explain what a batch assignment is and why you should use a bulk assignment.

The English name of the batch assignment is mass assignment, and the so-called bulk assignment is when we send an array to the model class to create the new model instance (usually the form request data), we can do it in the following way simply:

$post = Post::create (Input::all ());

Instead of setting property values as one with the Save method, if the model has a lot of properties, using Save is a nightmare with wood.

But things are always relative, using bulk assignment is convenient, but it also poses a security risk, and many times the model class has some property values that are not what we expect to be modified by batch assignment, such as the user model has a User_type attribute, and if the user modifies its type to an administrator type by requesting data, This is clearly not allowed, and it is based on this consideration that the eloquent model class provides us with the $fillable and $guarded attributes, which we can view as "whitelist" and "blacklist", and attributes defined in $fillable can be assigned by a batch assignment. Attributes that are defined in $guarded are filtered out in bulk assignment.

So what if we really want to modify the attributes defined in $guarded? The answer is to use the Save method.

Also note that the $fillable and $guarded methods can only be defined at the same time, the reason is very simple, not black or white, define a different one is OK.

The visible batch assignment not only provides convenience for us to create the model, but also avoids the hidden danger and improves the security of the system.

Let's show you how to use the batch assignment. First, define the $guarded properties in the post model as follows:

protected $guarded = [' views ', ' user_id ', ' updated_at ', ' created_at '];
Then implement the logic for creating the model instance in the controller:

$input = [
' title ' => ' Test 5 ',
' Content ' => ' test content ',
' cat_id ' =>1,
' Views ' =>100,
' user_id ' =>2
$post = Post::create ($input);
DD ($post);

2, update the model
2.1 Updating the model with the Save method

The Save method can also be used to update the model, to update the model data, to get the model instance, to modify the model properties, and then to save by calling the Save method:

$post = Post::find (1);
$post->title = ' Test 1 title ';
if ($post->save ()) {
Echo ' updates the article successfully. ';
Echo ' Update article failed. ';

2.2 Updating data using the Update method

Corresponding to create, the eloquent model class also supports updating data using the Update method, which also uses bulk assignments:

$input = [
' title ' => ' Test 6 title ',
' Content ' => ' test Content 6 ',
' cat_id ' =>1,
' Views ' =>200,
' user_id ' =>1
$post = Post::find (6);
if ($post->update ($input)) {
Echo ' updates the article successfully. ';
DD ($post);
Echo ' Update article failed. ';

1, delete the model
1.1 Deleting a model with delete

Deleting a model is simple, get the model instance you want to delete, and then call the Delete method:

$post = Post::find (5);
if ($post->delete ()) {
Echo ' Deletes the article successfully. ';
Echo ' failed to delete the article. ';

The method returns TRUE or false.
1.2 Using destroy to delete a model

Of course, if you know the model ID you want to delete, you can destroy it directly by using a simpler method:

$deleted = Post::d Estroy (5);

You can also delete multiple models at once by passing in multiple model IDs:

$deleted = Post::d Estroy ([1,2,3,4,5]);

The call to the Destroy method returns the number of records that were deleted.

1.3 Using the Query Builder to delete the model

Now that the eloquent model itself is the Query Builder, you can also use the Query Builder style to delete the model, for example, if we want to delete all articles with 0 browsing numbers, you can use the following methods:

$deleted = models\post::where (' views ', 0)->delete ();

Returns the number of articles that were deleted.
1. Query scope

Eloquent also supports the encapsulation of some commonly used queries into model methods, easy to call, we call it "query scope", the implementation of the query scope is very simple, just add a scope prefix before the model method, such as we often need to get the highest number of browsing articles, we can use this mechanism to implement- -Define a Scopepopular method in post:

Public Function Scopepopular ($query)
Return to $query->where (' views ', ' >= ', 100);

Accordingly, we define the test code in the controller as follows:

$posts = Post::p opular ()->orderby (' views ', ' desc ')->get ();
foreach ($posts as $post) {
Echo ' &lt; '. $post->title. ' &gt; '. $post->views. ' Views<br> ';
2. Model Events

Eloquent also supports model events-triggering events when the model is created, updated, or deleted, eloquent currently supports eight types of events: creating, created, updating, updated, saving, saved, deleting, deleted.

Deleting and deleted are well understood to trigger when the model is deleted, deleting before the delete operation, deleted after the deletion completes.

When the model is created, the saving, creating, created, and saved are executed sequentially, and the saving, updating, updated, and saved are executed sequentially when the model is updated. Whether you use a bulk assignment (create/update) or call the Save method directly, the corresponding event is triggered (provided that the corresponding model event is registered).

You can register the model event in any place you like, and here we choose to register in the boot method of the service provider Appserviceprovider:

Post::saving (function ($post) {
Echo ' Saving event is fired<br> ';

Post::creating (function ($post) {
Echo ' Creating event is fired<br> ';

post::created (function ($post) {
Echo ' created event is fired<br> ';

Post::saved (function ($post) {
Echo ' Saved event is fired<br> ';

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