3. in-depth understanding of LaravelEloquent (3)-relationship between models (Association)

Source: Internet
Author: User
3. in-depth understanding of LaravelEloquent (3)-Inter-model relationship (association) in-depth understanding of Laravel Eloquent (3)-Inter-model relationship (Association)

In this article, I will join you in learning the most complex and difficult part of Eloquent-the relationship between models. The official English document is Relationships. I personally think it is better to translate it into a "relationship between models" than the current "Association.

What is Eloquent?

Eloquent is an ORM called Object Relational ING. it is translated as "Object relationship ing" (if you only treat it as the Database Relational action Layer array library Abstraction Layer, it is too small to look at it ). The so-called "object" refers to the "Model" mentioned in this article, and the object relationship ing refers to the relationship between models. English document: http://laravel-china.org/docs/eloquent#relationships

Next, let's start learning one by one.

One-to-one relationship

As the name suggests, this describes the one-to-one relationship between two models. This relationship does not require an intermediate table.

Assume that we have two models: User and Account, which correspond to the registered users and consumers respectively. they are in a one-to-one relationship. if we want to use the one-to-one relationship method provided by Eloquent, the table structure should be as follows:

user: id ... ... account_id account: id ... ... user_id

Suppose we need to query the information of the corresponding Account table in the User model, the code should be like this. '/App/models/User. php ':

 hasOne('Account', 'user_id', 'id');   } }

Then, how should we use this relationship? As follows:

$account = User::find(10)->hasOneAccount;

The obtained '$ account' is an instance of the 'account' class.

The most difficult part here is the subsequent settings of foreign_key and local_key. you can remember that in the User class, no matter who hasOne is, the second parameter is 'user _ id ', the third parameter is generally 'id '. Because the previous 'Find (10) 'has locked id = 10, the corresponding SQL of this function is: 'select * from account where user_id = 10 '.

This code not only demonstrates how to use a one-to-one relationship, but also conveys three pieces of information, which is my advice for using Eloquent:

1. specify the table name in each Model.

2. the relationship like has one account is written as 'hasoneaccount () 'instead of simply 'account ()'

3. write full parameters every time you use the relationship between models. do not omit them.

Correspondingly, if belonsto () is used, it should be written as follows:

 belongsTo('User', 'user_id', 'id');   } }
One-to-multiple relationship

After learning the basic method of using one-to-one relationships, the following relationships are much simpler.

We introduce a new Model: Pay, payment record. The table structure should be as follows:

user: id ... ... pay: id ... ... user_id

There is a one-to-multiple relationship between User and Pay. In other words, a User can have multiple Pay. in this way, only one 'user _ id' field exists in the Pay table. '/App/models/User. php ':

 hasMany('Pay', 'user_id', 'id');   } }

Then, how should we use this relationship? As follows:

$accounts = User::find(10)->hasManyPays()->get();

The obtained '$ accounts' is an instance of the 'illuminate \ Database \ Eloquent \ collect' class. You should have noticed that this is not a simple '-> hasoneaccount' but'-> hasManyPays ()-> get () '. why? This is 'hashid', which operates on a collection of objects.

The usage of the corresponding belonsto () is the same as that in the previous one-to-one relationship:

 belongsTo('User', 'user_id', 'id');   } }
Many-to-many relationship

The multi-to-many relationship is completely different from the previous one, because many redundant data may exist in the multi-to-many relationship, and the existing tables cannot be stored.

We define two models: Article and Tag, which respectively represent articles and tags. they are multi-to-many relationships. The table structure should be as follows:

article: id ... ... tag: id ... ... article_tag: article_id tag_id

Use in Model:

 belongsToMany('Article', 'article_tag', 'tag_id', 'article_id');   } }

Note that the third parameter is the id of the class, and the fourth parameter is the id of the class of the first parameter.

Use the same as hascript:

$tagsWithArticles = Tag::take(10)->get()->belongsToManyArticle()->get();

Here we will get a very complex object. you can 'Var _ dump () 'on your own ()'. Let's talk about it. after 'Var _ dump () ', right-click Chrome and choose "View Source Code" to see the neat object/array expansion.

Here we will show you a rare usage ):

public function parent_video() {     return $this->belongsToMany($this, 'video_hierarchy', 'video_id', 'video_parent_id'); } public function children_video() {     return $this->belongsToMany($this, 'video_hierarchy', 'video_parent_id', 'video_id'); }

Yes. you are not mistaken. you can belongsToMany yourself.

Other relationships

Eloquent also provides the "one-to-many association", "Multi-State Association", and "multi-many-to-multi-association" features, we have mastered the basic concepts and usage of the relationship between the Eloquent models. The remaining several less commonly used methods will be used for further exploration.

Important: link pre-loading

You may have discovered that, in a one-to-one relationship, if we need to query 10 users at a time and carry the corresponding Account, we need to input 1 + 10 SQL statements to the database, the performance is poor. We can use an important feature, link preload: http://laravel-china.org/docs/eloquent#eager-loading

Directly run the code:

$users = User::with('hasOneAccount')->take(10)->get()

The generated SQL statement looks like this:

select * from account where id in (1, 2, 3, ... ...)

In this way, 1 + 10 SQL statements become 1 + 1, and the performance is greatly increased.


This is the end of the Laravel Eloquent series. We recommend that you continue to learn about soft deletion and conversion to arrays/JSON.

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.