The eloquent relationship model of Laravel five functions

Source: Internet
Author: User

Eloquent is Laravel's original ActiveRecord is implemented, built on the Laravel fluent Query builder, so the eloquent class and the fluent class are the same, The ability to implement complex SQL statements and very visually express the relationship between tables and tables

ActiveRecord also belongs to the ORM layer, which was first proposed by rails, followed by the standard ORM Model: Table maps to records, records mapped to objects, fields mapped to object properties. Together with the naming and configuration conventions followed, the operation of the model can be implemented very quickly and is simple and understandable.

The main ideas of ActiveRecord are:

1. Each database table corresponds to the creation of a class, each object instance of the class corresponds to a row of records in the database, and usually each field in the table has a corresponding field in the class;
2. ActiveRecord is also responsible for persisting itself, encapsulating access to the database in ActiveRecord, i.e. curd;
3. ActiveRecord is a domain model that encapsulates some of the business logic;

Now let's talk about the application of ActiveRecord in Laravel

About the eloquent method and its operation can be specific to see the document, here we mainly explain the relationship between the table

One-to-one relationship (one-to-one relationship)
A relationship between two tables in a relational database in which a single row in the first table can relate only to one row in the second table, and one row in the second table can only be related to one row in the first table.
If we had a user table and a Passport table, it was one-to-one relationship.

Let's start by expressing this relationship in our user class (for manipulating the user table)

class User extends eloquent  {          public  function passport ()          {                  return $this->has_one ( ' Passport '); // describes the Passport  for each user who has a corresponding         }  }  

What should we do if we want a passport with a user ID of 1?

 $user = user::find (1 ); //  Instantiate the user table  if   (Is_null ($user)) {echo   " no User found!   "          ;   return  ;  if  ($user->passport) {//  $user->passport will get $user corresponding Passport instance , and then get the number  echo  the user ' s passport num  ber is   ". $user->passport->number; }  

Take a look at our Passport class (for the operation of the Passport table), there is a foreign key user_id

class   Passport extends eloquent  {          public  function User ()          {                  return $this->belongs_to ('User'); // so we can express the user_id this foreign key corresponds to the user table           }  }  

If we're going to get the name of the user it's pointing to through a passport

$passport = Passport::find (1);  echo $passport->user->name;  

It's so simple! Laravel is so convenient! If you have used other PHP frameworks, you will feel it!


One-to-many relationship (One-to-many relationships)
A relationship between two tables in a relational database in which a single row in the first table can relate to one or more rows in the second table, but one row in the second table can only be related to one row in the first table.
If we have a sports team table, there are athletes with many athletes, each athlete belongs to a group

Table Team

class Team extends eloquent  {      public  function palyers ()      {          return $Has_many (' Player ');      }  }  

Table Players

class Player extends eloquent  {      public  function Team ()      {          return $this->belongs_to (  'Team');      }  }  

Then let's see how to get all the members of a group?

$team = Team::find (1);   = $team->palyers (),get();   foreach  as $player)  {          '$play->name is on Team $team->name';  }  

Many-to-many relationships (Many-to-many relationships)
A relationship between two tables in a relational database in which one row in the first table can relate to one or more rows in the second table. One row in the second table can also be related to one or more rows in the first table. To represent a many-to-many relationship, you must create a third table, often called a junction table, that divides a many-to-many relationship into two one-to-many relationships.
If there were such three sheets

Each student can choose any course, and each course can be selected by any student.
Now let's see how we define model.
Model of the Student table

class Student extends eloquent  {          public  function courses ()          {                  return $->has_many_and_ Belongs_to ('Course');          }  }  

Model of the course table

class Course extends eloquent  {          public  function students ()          {                  return $->has_many_and _belongs_to ('Student');          }  }  

Let's use our model by finding an elective course for students with ID 1

$student = Student::find (1); if(Is_null ($student)) {echo"no such student";  Exit }    if(! $studentcourses) {echo"student: $student->name no elective courses. ";  Exit }  Else  {          foreach($student->courses as$course) {echo"Students: $student->name elective courses are: $course->name"; }  }  

Then we'll go through the course and find out all the students he has.

$course = Course::find (1); if(Is_null ($course)) {echo"no This course";  Exit }  if($coursestudents) {          foreach($course->students as$student) {echo"This course: $course->name elective students are: $student->name"; }  }  Else{echo"No students are currently enrolled in the course!";  Exit }  

What should we do if we want to add information to a course that is not subject to elective?

$course = Course::find (N);   if (Is_null ($course))  {          " The course does not exist!"}  "          exit;  }   = Array (          'name'' apricot pear ';  );    $course->students ()->insert ($new _student);  

The eloquent relationship model of Laravel five functions

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.