Describes how to use Eloquent object ing in the Laravel framework of PHP. laraveleloquent_PHP tutorial

Source: Internet
Author: User
Describes how to use Eloquent object ing in the Laravel framework of PHP, laraveleloquent. Describes the use of Eloquent object link ing in the Laravel framework of PHP, laraveleloquent zero, and what is EloquentEloquent is Laravel's ORM, that is, ObjectRelationalMapping. describes the use of Eloquent object link ing in the larav, laraveleloquent

0. what is Eloquent?
Eloquent is Laravel's 'orm ', that is, 'object Relational mappings', Object relationship ING. The emergence of ORM is to help us make database operations more convenient.

Eloquent allows a 'model class' to correspond to a database table and encapsulates a lot of 'function' at the underlying layer, which makes it very convenient for the Model class to call.
Let's take a look at the following code:

<?phpclass Article extends \Eloquent {protected $fillable = [];}

'Protected $ fillable = []; 'this line of code has no value here and is automatically generated by generator. we will not discuss it here.

This class is simply no longer simple, with no namespace specified and no constructor. if that line of meaningless code is not counted, this file has only two practical things: 'article' and '\ Eloquent '. Yes, Eloquent is so awesome. you only need to inherit the Eloquent class to do a lot of things like 'first () find () where () orderBy, this is the powerful power of object-oriented.

I. basic use of Eloquent
Eloquent documents in:

I will directly show the code of several common use cases of Eloquent.

Find the article with id 2 and print its title

$article = Article::find(2);echo $article->title;

Search for the article titled "I am the title" and print the id

$ Article = Article: where ('title', 'I am title')-> first (); echo $ article-> id;

Query all articles and print all titles cyclically

$ Articles = Article: all (); // The $ articles obtained here is a collection of objects. you can add '-> toArray ()' to the end of the object to change it to a multi-dimensional array. Foreach ($ articles as $ article) {echo $ article-> title ;}

The search id ranges from 10 to 10 ~ All articles between 20 and print all titles

$articles = Article::where('id', '>', 10)->where('id', '<', 20)->get();foreach ($articles as $article) {  echo $article->title;}

Query all articles and print all titles cyclically. Sort by updated_at in reverse order.

$articles = Article::where('id', '>', 10)->where('id', '<', 20)->orderBy('updated_at', 'desc')->get();foreach ($articles as $article) {  echo $article->title;}

Basic usage points
1. each class that inherits Eloquent has two 'fixed use' Article: find ($ number) ''' Article: all ()', the former will get an object with the value obtained from the database, and the latter will get a collection of objects containing the entire database.

2. all intermediate methods, such as 'Where () ''' orderBy () ', support both 'static' and 'non-static chains', that is, 'Article :: where ()... 'and 'article ::.... -> where ()'.

3. all 'unfixed use' calls require an operation to 'finalize'. There are two 'final operation' in this tutorial: '-> get () 'and'-> first ()'.

2. Intermediate operation flow
Builder can be directly translated into the constructor, but "intermediate operation stream" is easier to understand, because database operations are mostly chained.

For the intermediate operation flow, see the code:

Article::where('id', '>', 10)->where('id', '<', 20)->orderBy('updated_at', 'desc')->get();

In this code, ': where ()-> orderBy ()' is the intermediate operation stream. The intermediate operation flow is understood in an object-oriented way and can be summarized into one sentence:

Create an object, modify its attributes, and use an operation to trigger database operations.
How to find clues about the intermediate operation flow

There is almost no valuable information in the intermediate operation stream. how can we find this stuff? Simple: use the following code:

$ Builder = Article: where ('title', "I am the title")-> title;

Then you will see the following error:

Why is an error? Because 'Article: where () 'is still a 'builder' object, it is not a 'article' object, and 'title' cannot be taken directly '.

Terminator method

The terminator method refers to triggering the final database query operation after processing a Eloquent object by N intermediate stream operation methods to obtain the return value.

'First () ''' get () ''' paginate () ''' count () ''' delete () 'is a lot of terminator methods, they will appear at the end of the intermediate operation stream, and call the SQL statement to the database to obtain the returned data. after processing, they will return a Article object or a set of Article objects.

Complex usage example

The code is as follows:

Article: where ('id', '>', '000000')-> where ('id', '<', '20140901 ') -> orWhere ('top', 1)-> belongsToCategory ()-> where ('Category _ level', '>', '1')-> paginate (10 );

III. relationship between models (Association)
1. 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_idaccount: 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 ':

<?phpclass User extends Eloquent {  protected $table = 'users'; public function hasOneAccount() {   return $this->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). 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:

<?phpclass Account extends Eloquent { protected $table = 'accounts';  public function belongsToUser() {  return $this->belongsTo('User', 'user_id', 'id'); }}

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

<?phpclass User extends Eloquent {  protected $table = 'users'; public function hasManyPays() {  return $this->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:

<?phpclass Pay extends Eloquent { protected $table = 'pays';  public function belongsToUser() {  return $this->belongsTo('User', 'user_id', 'id'); }}

3. many-to-many relationships

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:

<?phpclass Tag extends Eloquent { protected $table = 'tags';  public function belongsToManyArticle() {  return $this->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:

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.

Articles you may be interested in:
  • The relationship between Eloquent and Laravel 5 framework learning
  • Eloquent (Laravel's ORM) for laravel 5 framework learning)
  • Differences between some labels of section in Laravel template engine Blade
  • Detailed description of features released by Laravel 5.0
  • Laravel enables user registration and logon
  • We recommend several plug-ins used to develop Laravel using Sublime Text.
  • Laravel View & Response
  • Installing Laravel
  • Introduction to Laravel
  • Detailed description of Laravel framework form verification
  • Methods for extending functions and extending custom classes in the Laravel framework
  • Laravel framework route configuration summary and setup skills
  • PHP development framework Laravel database operation method summary

Restore zero, what is Eloquent is Laravel's 'orm ', that is, 'object Relational ING', Object relationship...

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