Eloquent Object relational mapping in PHP's laravel framework, laraveleloquent_php tutorial

Source: Internet
Author: User
Tags sublime text

Eloquent Object relational mapping in PHP's Laravel framework is used, laraveleloquent


0. What is eloquent
Eloquent is the Laravel ' ORM ', which is ' Object Relational Mapping ', which is a relational mapping of objects. The advent of ORM is to help us make the operation of the database more convenient.

Eloquent lets a ' model class ' correspond to a database table and encapsulates a lot of ' function ' in the bottom layer, making it very easy for the model class to invoke.
Take a look at the following code:

<?phpclass article extends \eloquent {protected $fillable = [];}

' Protected $fillable = []; ' This line of code does not have any value here, it is generator automatically generated, we do not discuss here.

This class is simply too simple to specify a namespace, no constructors, and if that line of meaningless code is not counted, the file has only two meaningful things: ' article ' and ' \eloquent '. That's right, eloquent is such a dick. To inherit the eloquent class, you can do a very, very large number of things, such as ' first () find () (), and that is the power of object-oriented.

I. 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 title" and print the ID

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

Check out all the articles and cycle through all the headings

$articles = Article::all (); The $articles obtained here is a collection of objects, which can be appended with '->toarray () ' to become multidimensional arrays. foreach ($articles as $article) {  echo $article->title;}

Find all the articles in 10~20 between IDs and print all titles

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

Check out all the articles and cycle through all the headings, sorted in reverse order Updated_at

$articles = article::where (' id ', ' > ', ten)->where (' id ', ' < ', ')->orderby (' Updated_at ', ' desc ')->get (); foreach ($articles as $article) {  echo $article->title;}

Basic use Points
1. Each class that inherits the eloquent has two ' fixed usage ' article::find ($number) ' Article::all () ', which gets an object with the values taken out of the database, which gets a collection of objects containing the entire database.

2. All intermediate methods such as ' Where () ' () ' () ' are able to support both ' static ' and ' non-static chaining ' methods, i.e. ' article::where (... ') and ' Article::....->where () '.

3. All ' non-fixed usage ' calls end up with an action to ' close ', with two ' finishing touches ' in this tutorial: '->get () ' and '->first '.

Second, intermediate operation flow
The word Builder can be translated into a constructor, but the "intermediate flow" is easier to understand, because database operations are mostly chain-operated.

For an intermediate operation flow, see the code:

Article::where (' id ', ' > ', ten)->where (' id ', ' < ', ')->orderby (' Updated_at ', ' desc ')->get ();

This Code of ':: Where ()->where ()->orderby () ' is the intermediate operation flow. The intermediate operation flow is understood by an object-oriented approach, which can be summed up in one sentence:

Creates an object, modifies its properties, and then triggers the database operation with an action.
How to find the clues to the intermediate operation flow

Intermediate operation Flow This thing, there is hardly any valuable information in the document, so how do we find this thing? Very simple, use the following code:

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

Then you will see the following error:

Why is there an error? Because ' Article::where ' is still the ' Builder ' object, not a ' article ' object, and cannot take ' title ' directly.

"Terminator" method

The so-called "Terminator" method, refers to the N-intermediate operation flow method to a eloquent object after processing, triggering the final database query operation, get the return value.

' First () ' Get () ' Paginate () ' Count () ' Delete () ' is used by some of the more "Terminator" methods, they will appear in the middle of the flow of operations, the SQL to the database, get the return data, processed to return a A collection of article objects or a group of article objects.

Examples of complex usages

Copy the Code code as follows:

Article::where (' id ', ' > ', '->where ') (' id ', ' < ', ' Max ')->orwhere (' Top ', 1)->belongstocategory ()- >where (' Category_level ', ' > ', ' 1 ')->paginate (10);

Iii. Relationship between models (association)
1. One-to-one relationship

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

If we have two models: User and account, which correspond to registered users and consumers, they are one-to-two relationships, then if we want to use the one-to-one relationship method provided by eloquent, the table structure should look like this:

User:id ... account_idaccount:id ... user_id. "

Suppose we need to query the User model for the corresponding account table information, then the code should be like this. '/app/models/user.php ':

<?phpclass User extends Eloquent {  protected $table = ' users '; public function Hasoneaccount () {   return $this-& Gt;hasone (' account ', ' user_id ', ' id '); }}

Then, when we need to use this relationship, how to use it? As follows:

$account = User::find (Ten)->hasoneaccount;

The resulting ' $account ' is an instance of the ' Account ' class.

The hardest part here is the two Foreign_key and Local_key settings in the back, and you can remember this: in the User class, the second argument is ' user_id ', and the third parameter is usually ' ID ', regardless of who hasOne. Since the previous ' find (10) ' has locked the ID = 10, the corresponding SQL for this function is: ' SELECT * from account where user_id=10 '.

This code, in addition to showing a one-to-one relationship to how to use, also conveys three points of information, but also for the use of eloquent when you are recommended:

(1). Table names are specified in each Model

(2). Has a relationship such as "hasoneaccount ()" Rather than the simple ' account () '

(3). Write full parameters each time you use the relationship between models, do not omit
Correspondingly, if you use the Belongsto () relationship, you should write this:

<?phpclass account extends Eloquent {protected $table = ' accounts ';  Public Function Belongstouser () {  return $this->belongsto (' User ', ' user_id ', ' id ');}}

2. One-to-many relationships

Learning the basic method of using a one-to-one relationship before, the following relationships are much simpler.

We introduce a new model:pay, payment record. The table structure should look 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 ':

<?phpclass 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 to use it? As follows:

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

The resulting ' $accounts ' is an instance of the ' Illuminate\database\eloquent\collection ' class. You 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 use of the corresponding Belongsto () is the same as the 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

Many-to-many relationships are completely different from previous relationships, because many-to-many relationships can result in a lot of redundant data, which is not available with the tables that were brought in before.

We define two models: article and tag, each representing articles and tags, and they are many-to-many relationships. The table structure should look like this:

Article:id ... article_tag:article_id tag_id. Tag:id .....

Used 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 this class, and the fourth parameter is the ID of the class that is the first parameter.

Use the same as Hasmany:

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

Here you get a very complex object that you can ' var_dump () ' yourself. To tell you a trick, ' var_dump () ', with Chrome right-click "View Source", you can see very neat objects/arrays unfold.

Here we show you a rare usage (artifice):

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 can belongstomany yourself if you don't read it right.
Other relationships

Eloquent also provides a "far layer one-to-many association", "Polymorphic Association" and "polymorphism of many-to-many associations," the other three uses, through the above study, we have mastered the eloquent model relationship between the basic concepts and use of methods, The rest of the less common methods will be left until we use the time to explore it ourselves.

Important tip: Relationship pre-loading
You may have found that in a one-to-one relationship, if we need to query out 10 User at a time and bring the corresponding account, then we need to hit the database 1 + 10 SQL, so performance is very poor. We can use an important feature, the relationship preload: http://laravel-china.org/docs/eloquent#eager-loading

Directly on the code:

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

The resulting SQL would look like this:

SELECT * from account where ID in (1, 2, 3, ...)

This Way 1 + 10 SQL becomes 1 + 1, and the performance is greatly increased.

Articles you may be interested in:

    • Eloquent relationship of Laravel 5 Framework Learning
    • Laravel 5 Framework Learning eloquent (Laravel's ORM)
    • Laravel template engine Blade The difference of some of the tags in section
    • Laravel 5.0 release new version features
    • Laravel Enabling user Registration and Login
    • Recommended several plug-ins used to develop Laravel with Sublime Text
    • Learn Laravel with me view & Response
    • Follow me to learn Laravel installation Laravel
    • A quick introduction to learning laravel with me
    • Laravel Framework Form Verification
    • Laravel extending functions and extending custom classes in the framework
    • Laravel Framework Routing configuration summary, Setup tips Daquan
    • Summary of PHP Development Framework Laravel Database operation method

http://www.bkjia.com/PHPjc/1104331.html www.bkjia.com true http://www.bkjia.com/PHPjc/1104331.html techarticle eloquent Object Relational mapping in PHP's Laravel framework is used, Laraveleloquent 0, what is eloquent eloquent is the ' ORM ' of Laravel, i.e. ' Object relational Mapping ', object relationship ...

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