Describes how to use Eloquent object ing in the Laravel framework of PHP, laraveleloquent

Source: Internet
Author: User

Describes how to use Eloquent object ing in the Laravel framework of PHP, 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: http://laravel-china.org/docs/eloquent

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

Copy codeThe 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 ... ...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 ':

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

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

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.