Laravel5.1 document introduction -- the most powerful and hard-to-understand LaravelEloquentORM part: Data relations

Source: Internet
Author: User
Laravel5.1 document introduction-the most powerful and hard-to-understand LaravelEloquentORM part: Data relationship introduction

As we all know, data tables can be associated. Eloquent ORM replaces table operations with data model operations. in this case, the associated query of tables is also called the Association query between models in Eloquent, this is the main content of this chapter;

Eloquent supports the following six types of table relationships:

  • One To One (One-To-One)

  • One To multiple)

  • Comparison To parallelism (Many-To-Many)

  • Has tables Through (one-to-multiple cross-table)

  • Polymorphic Relations (belonsto polymorphism)

  • Unable To parse Polymorphic Relations (belongsto polymorphism)

The first three relationships do not need to be explained much (please use Baidu). This place requires a lot of patience and efforts to make yourself accustomed to object thinking. do not use SQL for the time being, after a period of training, you will find it very useful;

Of course, some people also say that because the Eloquent is too powerful, it will bring a lot of things to load each time, which will affect the efficiency (the actual effect is nothing, please tell me if you are not satisfied with the data ), however, code writing efficiency, readability, and maintainability can be said to be a qualitative leap. Therefore, we strongly recommend that you use the code first.

I learned this chapter at the earliest, but the tutorial was written at the latest. because of the complicated relationships, I am a product. I should be able to explain the complicated things clearly, let's take a look at the most powerful ORM on the planet: Eloquent

Basic concepts

First, let's see how it is used:

$user->posts()->where('active', 1)->get();

This is how many articles have been published by the $ user object (the status is published ).

We can see that posts () is a $ user method here, so to use Association query, you must first define the relationship (method) in the $ user model );

One-to-one

From this figure, we can see that to use the Eloquent model relationship, the first step is to define the model relationship in the model, the second step is to prepare the correct table for the database; the third part is to use the query method, the fourth part is to use the binding and unbinding methods. our subsequent model relationships follow this process to understand and explain;

Key point: Observe the chart repeatedly! Define model definition User model
namespace App;use Illuminate\Database\Eloquent\Model;class User extends Model{        public function phone()    {        return $this->hasOne('App\Phone');    }}
Define Phone model
namespace App;use Illuminate\Database\Eloquent\Model;class Phone extends Model{    public function user()    {        return $this->belongsTo('App\User');    }}

Note: When defining a model, pay attention to the singular and plural method names. if "1" is used as the singular number and if "more" is used as the plural number, it is not easy to confuse and make a mistake. HasOne () has many methods similar to this link binding method, so you need to be familiar with it in use. pay attention to it.

Data table

Note that there is no intermediate table in this example for foreign keys and intermediate tables;

Link query model link method query
$user->posts()->where('active', 1)->get();

This is the model method query. $ user-> posts () is a DQB object, which can be followed by various database query methods;

Dynamic attribute query
$user->posts;

You can use the link as an attribute to directly find a collection set. The disadvantage is that it cannot be followed by the DQB method.

Both methods are frequently used and can be used as appropriate. (the same below is not explained)

Link binding and unbinding

The common binding method is save ();

The general method of disassociation is to dissociate () for the belongstoo relation, and to detach () for the belongsToMany relation ();

There are also some specific unbinding methods. let's talk about them in a separate relational model;

One-to-multiple

Unbind

If you want to bind through the belonsto relationship, you can use associate () to bind it, and finally save ,;

Many-to-many

Because belonsto is changed to belongsToMany, the corresponding binding method is changed to attach () and detach (). Note that the object ID is entered here and can be bound in batches in the form of arrays;

The save () method still applies to link binding;

Actions on the intermediate table

Because many-to-many relationships have an intermediate table, Eloquent can operate other fields in the intermediate table in addition to the foreign keys by default. See the example below:

App\User::find(1)->roles()->save($role, ['expires' => $expires]);
$user->roles()->attach($roleId, ['expires' => $expires]);
$user->roles()->attach([1 => ['expires' => $expires], 2, 3]);
$user->roles()->sync([1 => ['expires' => true], 2, 3]);
Sync () method

Sync means synchronization, which means that the intermediate table will be removed in the same way as the parameters in sync (). any parameters not written in the parameters can be used to unbind them;

Has tables Through (one-to-multiple cross-table)

In fact, this is only a quick query method. for the figure, you can first query the User through the Conuntry and then query the Post through the User. now you can directly query the Post through the Country;

Generally, the relationship between Country and User, User, and Post tables is established in advance. at this time, you can use hasManyThrough;

Polymorphic Relations (belonsto polymorphism)

Originally, belonsto can only belong to one type of object, just like a girlfriend can only belong to a boyfriend. now, a girlfriend can not only belong to a boyfriend, but also belongs to a father.

Joke: The most common application is the image. it can belong to multiple models and look at the image;

We found that the verb here becomes morphTo (), morphTo ();

First, take a short English lesson to improve your sense of language:

Morph refers to changing the form, which is also different from the transform of transformers, which is mainly changing the shape;

MorphTo (), morphMany (); in fact, it is in the form of belonsto () and hasMany () polymorphism. polymorphism means not only having a male ticket, but also a cool, a little "abnormal ";

About binding and unbinding

Associate () is not applicable to morphTo (); therefore, only save () can be used for one-way binding;

Dissociate () is not applicable to morphTo (). Therefore, only Photo instances can be deleted !! It does not matter if you delete the table (because there is no intermediate table)

This is not a natural design, but the current situation is as follows;

Unable To parse Polymorphic Relations (belongsto polymorphism)

This is the most typical application of tags. tags need to involve many-to-many relationships and problems related to different types of models. Therefore, they are belongsToMany + polymorphism;

See the figure. it can be bound and unbound;

Eager Loading (pre-Loading)

This is a simple question. you can understand it when you look at an instance:

$books = App\Book::all();foreach ($books as $book) {    echo $book->author->name;}

In case there are 10 thousand books, there will be 10 thousand cycles. each cycle will read the database once because the associated query $ book-> author-> name; is used, this means that the database should be read at least 10 thousand times, and the database cried.

The Eager Loading is used to make the database read before the loop:

$books = App\Book::with('author')->get();foreach ($books as $book) {    echo $book->author->name;}

Look, after adding a magic with (), all the data is read before foreach, and the following loop is only the read data, a total of two queries to the database !!

The Eager Loading can greatly relieve the database query pressure and is an important means of performance optimization! Multiple Eager Loading relationships

Add more joined tables at a time;

$books = App\Book::with('author', 'publisher')->get();
Nested Eager Loading
$books = App\Book::with('author.contacts')->get();

Read the author of the book and his contact information by the way.

Conditional Eager Loading

The above is the reading of the entire table, which is so good. In fact, sometimes we only need some records in the table:

$users = App\User::with(['posts' => function ($query) {    $query->where('title', 'like', '%first%');}])->get();

In this example, we have mentioned the closure statement multiple times, that is, adding a condition;

Lazy Eager Loading

Isn't the title self-contradictory? Again Lazy, and Eager?

Oh, in the lazy process, the eager loading is required:

$books = App\Book::all();if ($someCondition) {    $books->load('author', 'publisher');}
$books->load(['author' => function ($query) {    $query->orderBy('published_date', 'asc');}]);

Pay attention to this load (), which is used for collection;

Cross-model update timestamp

Simply put, when a comment is updated, the 'updated _ at' field of the article is also updated;

namespace App;use Illuminate\Database\Eloquent\Model;class Comment extends Model{    /**     * All of the relationships to be touched.     *     * @var array     */    protected $touches = ['post'];    /**     * Get the post that the comment belongs to.     */    public function post()    {        return $this->belongsTo('App\Post');    }}

Set the $ touches attribute;

Then, when you update the Comment, the 'updated _ at' field of the Post will also be updated;

For more information, visit Laravel 5.1.

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.