Laravel 5.1 Document Guide--laravel the most powerful and difficult part of eloquent ORM: data relations

Source: Internet
Author: User

Brief introduction

In fact, we all know that the data table can be correlated, eloquent ORM is the data model operation instead of table operations, then the table associated query, in eloquent here is the model of the association query, this is the main content of this chapter;

Eloquent one supports the following 6 types of table relationships:

    • One to one (one-to-one)

    • One to many (one-to-many)

    • Many to many (many-to-many)

    • has many Through (cross-table one-to-many)

    • Polymorphic relations (Belongsto polymorphism)

    • Many to many polymorphic relations (Belongstomany polymorphic)

The first three relationships is not much explanation (please Baidu), this place needs a lot of patience, and strive to get accustomed to the object of thinking, temporarily do not use SQL, practice a period of time will find very useful;

Of course, there are also people spit groove eloquent because too strong, resulting in each load with a lot of things, affecting efficiency (actual no impact, not to take the data with me), but in the code of the writing efficiency, readability, maintainability can be said to be qualitative leap, so it is strongly recommended to use first.

This chapter I learned the earliest, but the tutorial is written the latest, because all kinds of relationship is more complex, fortunately, I am a product origin, should be able to explain the complex things, let us come to know the most powerful orm:eloquent on the planet

Basic concepts

Let's see how it's used:

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

This is to find out how many articles he has published (status is published) by $user object.

We see that posts () is a method of $user here, so to use an associative query, you have to first define the relationship (method) in the $user model;

One

From this graph, 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, the third part uses the method of the query, the Forth part is the method of binding and unbind, and the subsequent model relationships are understood and explained according to this process;

Key points: Repeated observation diagram!

Defining the Model

Defining the user Model

Namespace App;use illuminate\database\eloquent\model;class User extends model{public        function Phone ()    {        return $this->hasone (' App\phone ');}    }

Defining the 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, the method name takes note of the plural, "one" is singular, "more" is used in the plural, so it is not easy to confuse the mistake. HasOne () similar to this relationship binding method has a lot, need to be familiar with in use, pay attention to observation.

Data Sheet

Mainly note that the foreign key and the intermediate table are these things, in this case there is no intermediate table;

Relationship Query

Model Relationship Method Query

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

This is the model method query, $user->posts () found here is a DQB object, can be followed by a variety of database query methods;

Dynamic Property Query

$user->posts;

You can use the relationship as a property, directly detect a collection set, the disadvantage is that the latter can not be followed Dqb method.

Both methods are commonly used, as appropriate, and (again, no longer explained)

Relationship binding and release

The universal binding method is save ();

The general lifting method, the relationship to Belongsto is dissociate (); The relationship to Belongstomany is detach ();

There are some specific methods of binding cancellation, which we then speak in a separate relational model;

One-to-many

Tied

If you want to bind through belongsto relationship, you can use Associate () to bind, finally save (),;

Many-to-many

Since Belongsto is replaced by Belongstomany, the corresponding binding method is replaced with attach () and detach (); Note that the object ID can be filled with array form.

The Save () method still applies to the relationship binding;

Operations on the intermediate table

Since many-to-many relationships have an intermediate table, eloquent can also operate on other fields in the intermediate table, in addition to the default on the foreign keys in the middle, to see an example:

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 is synchronization, meaning that the middle table will sync into sync () inside the parameters, not written in the parameters will be removed, it can be used to unbind;

has many Through (cross-table one-to-many)

In fact, this is just a quick query method, look at the picture, you can first through the Conuntry check the user, and then through the user check post, now you can country directly check post;

Usually country and user,user and post table relationships are established beforehand, this time you use Hasmanythrough;

Polymorphic relations (Belongsto polymorphism)

Originally Belongsto can only belong to a kind of object, like a girlfriend can only belong to a boyfriend; now, the girlfriend can not only belong to boyfriend, but also belong to the father-in-man.

Joking, the most common application or picture, can belong to a variety of models, look at the picture;

We find the verbs here become morphto (), Morphmany ();

First, a little English class, improve the sense of language:

The word morph is a change of form, called Metamorphosis, which is not the same as the transform of the Transformers, which is mainly a change in shape;

Morphto (), Morphmany (); In fact, Belongsto () and Hasmany () polymorphic form, polymorphism is not only a male ticket, but also a father-in-the-way, a bit "abnormal";

About binding and reconciling

Associate () does not apply to Morphto (); So it can only be bound in one Direction with Save ();

Regarding the Unbind, dissociate () also does not apply to Morphto (); So, only photo instance can be deleted!! It doesn't matter if it's deleted (because there's no intermediate table)

The feeling is not a very natural design, but the current investigation down the situation is this;

Many to many polymorphic relations (Belongstomany polymorphic)

The most typical application is the label, the label to involve many-to-many relationships, but also related to different types of model problems, so is belongstomany+ polymorphic;

Look at the picture, can be bound, can be untied;

Eager Loading (pre-loaded)

This is a very simple question, and you'll understand it by looking at an example:

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

In case of books there are 10,000, then the cycle will be 10,000 times, each cycle, because the correlation query $book->author->name; , will read the database once, meaning that at least 10,000 read the database, the database cried.

Eager Loading is to let the database reads occur before the loop:

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

See, add a magical with (), all the data in the foreach before the read out, the back of the loop is just read out the data, a total query database 2 times!!

Eager loading can greatly alleviate the database query pressure, is an important means of performance optimization!

Eager Loading Multiple relationships

is to add a few related tables at a time;

$books = App\book::with (' Author ', ' publisher ')->get ();

Nesting Eager Loading

$books = App\book::with (' author.contacts ')->get ();

Read the author of the book, and read the author's contact information by the way.

Conditional Eager Loading

It is said that the whole table of the entire table read out, too local tyrants, in fact, sometimes we only need to part of the table records:

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

The closure of the writing we have said many times, is to add a condition;

Lazy Eager Loading

Isn't the headline a contradiction? And lazy, and eager?

Oh, the original is in the lazy process to determine the need to eager loading:

$books = App\book::all (), if ($someCondition) {    $books->load (' Author ', ' publisher ');}
$books->load ([' Author ' = function ($query) {    $query->orderby (' published_date ', ' ASC ');}]);

Note this load (), which is used for collection;

Update timestamps across models

Simply put, is a comment update, by the way the article's ' Updated_at ' field has also been 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 is the comment belongs to.     *    /Public Function post ()    {        return $this->belongsto (' App\post ');}    }

Set $touches this property;

Then you update the comment, you will be the post of the ' Updated_at ' field also updated;

For more information, please visit: Laravel 5.1 Document Introduction

  • Related Article

    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.