0, what is eloquent
eloquent is Laravel's ' ORM ', the ' Object Relational Mapping ', the object-relational mapping. ORM appears to help us make the operation of the database easier.
Eloquent lets a ' model class ' correspond to a database table, and encapsulates a lot of ' function ' at the bottom so that the model class can be easily invoked.
Take a look at the following code:
<?php
class Article extends \eloquent {
protected $fillable = [];
}
' Protected $fillable = []; ' This line of code here has no value, is generator automatically generated, here we do not discuss.
This class is simply too simple to specify a namespace, no constructors, and if that line of meaningless code does not count, there are only two practical things in this file: ' Article ' and ' \eloquent '. Yes, eloquent is so good fried days, just to inherit a eloquent class, you can do ' a ' () find () where () by () "And so very many things, this is the powerful power of object-oriented."
Basic usage of eloquent
eloquent Chinese document in: http://laravel-china.org/docs/eloquent
Needless to say, I'll show you the code for several common uses of eloquent.
Find an article with ID 2 to print its title
$article = Article::find (2);
Echo $article->title;
Find the article titled "I am a title" and print the ID
$article = Article::where (' title ', ' I am the title ')->first ();
Echo $article->id;
Query all the articles and loop through all the headings
$articles = Article::all (); The $articles here is a collection of objects that can be followed by '->toarray () ' into a multidimensional array.
foreach ($articles as $article) {
echo $article->title;
}
Find all articles in the ID between 10~20 and print all headings
$articles = article::where (' id ', ' > ', ')->where (' id ', ' < ', ')->get ();
foreach ($articles as $article) {
echo $article->title;
}
Query out all articles and cycle through all headings, sorted by Updated_at reverse order
$articles = article::where (' id ', ' > ', ')->where (' id ', ' < ', ')->orderby (' Updated_at ', ' desc ')->get ();
foreach ($articles as $article) {
echo $article->title;
}
Basic points of Use
1. Each class that inherits eloquent has two ' fixed usage ' article::find ($number) ' Article::all () ', which gets an object with the value retrieved from the database, which gets a collection of objects that contain the entire database.
2. All intermediate methods, such as ' where () ' by ' () ', can support both ' static ' and ' Non-static chain ' calls, i.e. ' article::where () ... ' and ' Article::....->where () '.
3. All the ' unfixed usage ' calls eventually require an operation to ' finish ', and in this tutorial there are two ' closing operations ': '->get () ' and '->first () '.
Second, intermediate operation flow
Builder This word can be translated into a constructor, but the "intermediate operation Flow" is easier to understand, since database operations are mostly chain-operated.
Intermediate operation flow, see Code:
Article::where (' id ', ' > ', ')->where (' id ', ' < ', ')->orderby (' Updated_at ', ' desc ')->get ();
This code's ':: Where ()->where ()->orderby () ' is the intermediate operation flow. The intermediate operation flow is understood by object-oriented method, which can be summed up in one sentence:
Create an object and constantly modify its properties, and finally use an action to trigger the database operation.
How to find clues to the flow of intermediate operations
In the middle of the flow of this thing, there's hardly any valuable information in the document, so how do we find this thing? Quite simply, use the following code:
$builder = Article::where (' title ', "I am title")->title;
Then you will see the following error:
Why is there an error? Because ' article::where () ' is still the ' Builder ' object, is not ' Article ' object, can not directly take ' title '.
"Terminator" method
The so-called "Terminator" method refers to the processing of a eloquent object by N intermediate operation flow method, which triggers the final database query operation and gets the return value.
' The ' () ' Get () ' Paginate () ' Count () ' ' Delete () ' is a more "Terminator" method, they will appear at the end of the intermediate operation Stream, call SQL to the database, get the return data, and process the returned A collection of Article objects or a group of Article objects.
Examples of complex usages
Copy Code code as follows:
Article::where (' id ', ' > ', ' m ')->where (' id ', ' < ', ') '->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 a one-to-one relationship between the two models. This relationship does not require an intermediate table.
If we have two models: User and Account, respectively, for registered users and consumers, they are one-to-one relationships, so if we are going to use the one-to-one relational approach provided by eloquent, the table structure should be:
User:id ... account_id, account:id ... user_id.
Suppose we need to query the User model for the corresponding account table information, so the code should be. '/app/models/user.php ':
<?php
class User extends eloquent {
protected $table = ' users ';
Public Function Hasoneaccount ()
{return
$this->hasone (' account ', ' user_id ', ' id ');
}
Then, when we need to use this relationship, how do we use it? As follows:
$account = User::find (->hasoneaccount;)
The ' $account ' at this point is an instance of the ' Account ' class.
The hardest part here is the two Foreign_key and Local_key settings, which you can remember: in the User class, whoever hasone, the second parameter is ' user_id ', and the third parameter is usually ' ID '. Because the previous ' find (10) ' has locked id = 10, this function corresponds to the SQL: ' SELECT * from account where user_id=10 '.
This code, in addition to showing how to use a one-to-one relationship, also conveys three points of information, and is my advice for everyone to use eloquent:
(1). Table names are specified in each Model
(2). has one account such a relationship is written ' hasoneaccount () ' rather than simple ' account () '
(3). Write full parameters every time you use the relationship between models, do not omit
Accordingly, if you use the Belongsto () relationship, you should write this:
<?php
class Account extends eloquent {
protected $table = ' accounts ';
Public Function Belongstouser ()
{return
$this->belongsto (' User ', ' user_id ', ' id ');
}
2. A one-to-many relationship
Having learned the basics 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 like this:
User:id ... Pay:id ... user_id
User and Pay have a one-to-many relationship, in other words, a user can have multiple Pay, so there is only one ' user_id ' field in the Pay table. '/app/models/user.php ':
<?php
class User extends eloquent {
protected $table = ' users ';
Public Function hasmanypays ()
{return
$this->hasmany (' Pay ', ' user_id ', ' id ');
}
Then, when we need to use this relationship, how do we use it? As follows:
$accounts = User::find ()->hasmanypays ()->get ();
The ' $accounts ' at this point is an instance of the ' Illuminate\database\eloquent\collection ' class. We should also have noticed that this is not a simple '-> hasoneaccount ' but '->hasmanypays ()->get ', why? Because this is ' hasmany ', the operation is a collection of objects.
The corresponding Belongsto () is the same as the above one-to-one relationship:
<?php
class Pay extends eloquent {
protected $table = ' pays ';
Public Function Belongstouser ()
{return
$this->belongsto (' User ', ' user_id ', ' id ');
}
3. Multi-relationship
A many-to-many relationship is completely different from the previous one, because a many-to-many relationship can have a lot of redundant data, and you can't save it with a table that comes with it.
We define two models: Article and tag, which represent articles and tags, and they are many-to-many relationships. The table structure should be like this:
Article:id ...
Tag:id ... article_tag:article_id tag_id
Use in Model:
<?php
class 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 this class, and the fourth parameter is the ID of the class with the first argument.
Use the same as Hasmany:
$tagsWithArticles = Tag::take ()->get ()->belongstomanyarticle ()->get ();
Here you will get a very complex object that can be ' var_dump () '. To tell you a trick, ' Var_dump () ' Later, with the Chrome right button "View source code", you can see very neat object/array unfolded.
Here to show you a rare usage (Chine):
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 wrong, you can belongstomany yourself.
Other relationships
Eloquent also provides the three other uses of "far-level One-to-many Association", "Polymorphic Association" and "polymorphic Many-to-many Association", through which we have mastered the basic concepts and usage of the relationship between eloquent models, The remaining few methods that are not commonly used are left until we use them to explore ourselves.
Important Tip: Relationship preload
You may have found that in a one-to-one relationship, if we need to query out 10 User and bring the corresponding account, then we need to give the database 1 + 10 SQL, so the performance is very poor. We can use an important feature of the relationship preload: http://laravel-china.org/docs/eloquent#eager-loading
Directly on the code:
$users = User::with (' Hasoneaccount ')->take (a)->get ()
This is how SQL is generated:
SELECT * from account where ID in (1, 2, 3, ...)
This 1 + 10 SQL becomes 1 + 1, and the performance is greatly increased.