A pair of one or one pairs of one-to-many, Many-to-many, many-to-many practices about table relationships in Laravel

Source: Internet
Author: User
first about the relationship between tables and tables

1. A One-to-many
2. A One-to-many
3. Multiple to One
4. Multi-pair multi- parent table and child table

1. "One" is the parent table
2. One side of "many" is how a child table handles a one-to-many relationship

Building a field in a child table (foreign key) points to the parent table How to handle a many-to-many relationship

Establishing a middle table, transforming "many-to-many" relationship into "one-to-many" Case Analysis

Table One: User table (It_user)
Table II: User Details table (it_user_info)
Table III: Article table (it_article)
Table IV: Country tables (It_country)
Table five: User Role table (it_role)
① One-on-one
The User table (table i) and the Details table (Table II) are one-to-one relationships
② a pair of many
The User table (table i) and the article table (table III) are a one-to-many relationship
③ for one More
User table (Table i) and Country table (table IV) is the relationship between the multiple
④ more than the most
User table (Table i) and role table (table V) is a many-to-many relationship user table building and test data

DROP TABLE IF EXISTS ' it_user ';
CREATE TABLE ' it_user ' (
  ' id ' int ' unsigned not NULL auto_increment COMMENT ' primary key ',
  ' name ' varchar () DEFAULT NU LL COMMENT ' username ',
  ' password ' char (#) default null COMMENT ' password (does not use MD5) ',
  ' country_id ' int (one) default NULL,
  PRIMARY key (' id '),
  key ' Country id ' (' country_id ')
) Engine=myisam auto_increment=6 DEFAULT Charset=utf8;

------------------------------
-Records of It_user
------------------------------
INSERT into ' it_ User ' VALUES (' 1 ', ' xiaoming ', ' 123456 ', ' 1 ');
INSERT into ' it_user ' VALUES (' 2 ', ' Xiaomei ', ' 123456 ', ' 1 ');
INSERT into ' it_user ' VALUES (' 3 ', ' xiaoli-new ', ' 123 ', ' 1 ');
User Detail table and test data
------------------------------
--Table structure for it_user_info
------------------------------
DROP TABLE IF EXISTS ' it_user_info ';
CREATE TABLE ' it_user_info ' (
  ' user_id ' int (one) not null auto_increment,
  ' Tel ' char (one) DEFAULT null,
  ' email ' varchar (128) default NULL,
  ' addr ' varchar (255) default NULL,
  PRIMARY KEY (' user_id ')
) Engine=myisam auto_ increment=4 DEFAULT Charset=utf8;

------------------------------
--Records of It_user_info
------------------------------
INSERT Into ' It_user_info ' VALUES (' 1 ', ' 13012345678 ', ' xiaoming@163.com ', ' Beijing ');
INSERT into ' it_user_info ' VALUES (' 2 ', ' 15923456789 ', ' xiaomei@163.com ', ' Shanghai ');
INSERT into ' it_user_info ' VALUES (' 3 ', ' 18973245670 ', ' xiaoli@163.com ', ' Wuhan ');
Table of articles and test data
------------------------------
--Table structure for it_article
------------------------------
DROP TABLE IF EXISTS ' it_article ';
CREATE TABLE ' it_article ' (
  ' id ' int () NOT NULL auto_increment,
  ' title ' varchar (255) DEFAULT null,
  ' Content ' text,
  ' user_id ' int (one) DEFAULT NULL,
  PRIMARY key (' id '),
  key ' user_id ' (' user_id ')
engine= MyISAM auto_increment=4 DEFAULT Charset=utf8;

------------------------------
--Records of It_article
------------------------------
INSERT into ' It_article ' VALUES (' 1 ', ' The world is so big, I want to see ', ' wallet so small, always not enough ', ' 1 ');
INSERT into ' it_article ' VALUES (' 2 ', ' I want to bump into love ', ' It's touching the Ghost ', ' 2 ');
INSERT into ' it_article ' VALUES (' 3 ', ' hahaha ', ' Hee Hee ', ' 1 ');
National table and test data
------------------------------
--Table structure for it_country
------------------------------
DROP TABLE IF EXISTS ' it_country ';
CREATE TABLE ' it_country ' (
  ' id ' int () NOT NULL auto_increment,
  ' name ' varchar (255) DEFAULT null,
  PRIMARY K EY (' id ')
) Engine=myisam auto_increment=3 DEFAULT Charset=utf8;

------------------------------
--Records of It_country
------------------------------
INSERT into ' It_country ' VALUES (' 1 ', ' China ');
INSERT into ' it_country ' VALUES (' 2 ', ' USA ');
User Role Table building and test data
------------------------------
--table structure for it_role
------------------------------
DROP table IF EXISTS ' it_role ';
CREATE TABLE ' it_role ' (
  ' id ' int () NOT NULL auto_increment,
  ' name ' varchar (255) DEFAULT null,
  PRIMARY KEY ( ' id ')
engine=myisam auto_increment=5 DEFAULT Charset=utf8;

------------------------------
-Records of It_role
------------------------------
INSERT into ' it_ Role ' VALUES (' 1 ', ' development ');
INSERT into ' it_role ' VALUES (' 2 ', ' Test ');
INSERT into ' it_role ' VALUES (' 3 ', ' management ');
User and Role Intermediate table table and test data
------------------------------
--Table structure for it_user_role
------------------------------
DROP TABLE IF EXISTS ' it_user_role ';
CREATE TABLE ' it_user_role ' (
  ' user_id ' int () default null,
  ' role_id ' int (one) default null,
  KEY ' role_id ' ( ' role_id '),
  KEY ' user_id ' (' user_id ')
) Engine=myisam DEFAULT Charset=utf8;

------------------------------
--Records of It_user_role
------------------------------
INSERT Into ' It_user_role ' VALUES (' 1 ', ' 1 ');
INSERT into ' it_user_role ' VALUES (' 1 ', ' 2 ');
INSERT into ' it_user_role ' VALUES (' 1 ', ' 3 ');
INSERT into ' it_user_role ' VALUES (' 2 ', ' 1 ');
INSERT into ' it_user_role ' VALUES (' 3 ', ' 2 ');
preparatory work

1. Planning Routing
The following routes are written under routes/web.php:

ORM Association Relationship
Route::get ('/orm/relation/{mode} ', ' orm\usercontroller@relation ');

2. Writing relation method in app/http/controllers/orm/usercontroller.php

    Public function relation ($mode)
    {
        switch ($mode) {case
            ' 1_1 ':
            {
                //one-to-one

            } break
            ;
            Case ' 1_n ':
            {
                //a pair of multiple

            } break
                ;
            Case ' n_1 ':
            {
                //multiple to one

            } break
                ;
            Case ' N_n ':
            {
                //many to many

            } break
                ;
            default;
        }

    }

3, install debug Debugging Tools
3.1 Install using the composer command

Composer require  Barryvdh/laravel-debugbar

3.2, modify the config/app.php file, load Debugbar to laravel into the project, add the following configuration in the ' providers ' array:

Barryvdh\debugbar\serviceprovider::class,

In addition to installing the Debugbar debugging tools, you can also use Query sniffing: Edit the providers/appserviceprovider.php boot method by adding the following code

\db::listen (function ($query) {
    var_dump ($query->sql);
     Var_dump ($query->bindings);
     Echo ' <br> ';
 });

You can also print out the executed SQL statement. One-on-one 1. Create UserInfo Model Objects

Enter the cmd command line to enter the directory where the Laravel project executes the following command
php artisan Make:model Userinfo
Will generate userinfo.php 2, edit userinfo model files in the app directory

<?php

namespace App;

Use Illuminate\database\eloquent\model;

Class Userinfo extends Model
{
    protected $table  =  ' User_info ';
    protected $primaryKey = ' user_id ';
    protected $fillable = [' user_id ', ' tel ', ' email ', ' addr '];
    Public    $timestamps = false;
}
3, Write Usermodel, add a one-to-one approach
<?php

namespace App;

Use Illuminate\database\eloquent\model;

Class Usermodel extends Model
{
    protected $table = ' user '; the table name
    protected $primaryKey = ' id ';//primary key field, default is id< c6/>protected $fillable = [' name ', ' Password '];//the field that can be manipulated is public
    $timestamps = false;//If there are no created_at and updated_ in the datasheet ID field, $timestamps can not set, default to True public

    function Userinfo () {/
         * * @param [string] [name] [ Model class name that needs to be associated]
         * @param [string] [foreign] [parameter a field in the specified datasheet]
         *
        /return $this->hasone (' App\userinfo ', ' user_id ');
    }
4, write Usercontroller, call one-to-one method
    Public function relation ($mode)
    {
        switch ($mode) {case
            ' 1_1 ':
            {
                //one-to-one
                $data = Usermodel::find (1)->userinfo ()->get ();
                DD ($data);
            break;

            default;
        }

    }  
A pair of many 1. Create Article Model objects

Execute command
php artisan Make:model Article
Generate article.php file 2 under App , write article model file

<?php

namespace App;

Use Illuminate\database\eloquent\model;

Class Article extends Model
{
    protected $table = ' Article ';
    Protected $primaryKey = ' id ';
    protected $fillable = [' id ', ' title ', ' content ', ' user_id '];
    Public $timestamps  = false;
}
3, Write Usermodel, add a pair of multiple methods
Public Function artice ()
    {return
        $this->hasmany (' app\article ', ' user_id ');
    }
4, write Usercontroller, call a one-to-many approach
    Public function relation ($mode)
    {
        switch ($mode) {case
            ' 1_1 ':
            {
                //one-to-one
                $data = Usermodel:: Find (1)->userinfo ()->get ();
                DD ($data);
            break;
            Case ' 1_n ':
            {
                //one-to-many
                $data = usermodel::find (1)->artice ()->get ();
                DD ($data);
                break;

            Default;}}}

more to one 1. Create Country Model objects
Execute command

php artisan Make:model Country 2. Write Country model files

<?php

namespace App;

Use Illuminate\database\eloquent\model;

Class Country extends Model
{
    protected $table = ' Country ';   Real table name
    protected $primaryKey = "id";   Primary Key ID
    protected $fillable = [' id ', ' name '];    The field that is allowed to operate is public
    $timestamps  =false;//If there are no Created_at and updated_id fields in the datasheet, $timestamps can not set, default to True

}
3, Write Usermodel, add a more than one method
Public Function Country ()
{return
    $this->belongsto (' app\country ', ' country_id ');
}
4, write Usercontroller, call the method
Public function relation ($mode)
    {
        switch ($mode) {case
            ' 1_1 ':
            {
                //one-to-one
                $data = Usermodel:: Find (1)->userinfo ()->get ();
                DD ($data);
            break;
            Case ' 1_n ':
            {
                //one-to-many
                $data = usermodel::find (1)->artice ()->get ();
                DD ($data);
                break;
            Case ' n_1 ':
            {
                //multiple pairs of one
                $data = Usermodel::find (1)->country ()->get
                (); DD ($data);
                break;

            Default;}}}

many to many 1. Create Role Model Objects

Execute command
PHP artisan Make:model role
Execute command
php artisan Make:model user_role 2. Writing role model

<?php

namespace App;

Use Illuminate\database\eloquent\model;

Class Role extends Model
{
    protected $table = ' role ';
    Protected $primaryKey = "id";
    protected $fillable = [' name '];
    Public $timestamps  =false;

}
writing the User_role model

Because there are no primary key fields in the table, you need two fields to

<?php

namespace App;

Use Illuminate\database\eloquent\model;

Class User_role extends Model
{
    protected $table = ' user_role ';
    Public $timestamps  =false;

}
3, Write Usermodel, add many to many methods
    Public Function Role () {
        /
         * * * The first parameter: the corresponding class for the table to be associated
         * The second parameter: The table name of the middle table
         * Third parameter: The foreign key for the current table corresponding to the intermediate table
         * Fourth parameter: The table to be associated with the middle table corresponding to the foreign key
         *
        /return $this->belongstomany (' app\role ', ' user_role ', ' user_id ', ' role_id ');
    
4, write Usercontroller, call many to many methods
Public function relation ($mode)
{
    switch ($mode) {case
        ' 1_1 ':
        {
            //one-to-one
            $data = Usermodel:: Find (1)->userinfo ()->get ();
            DD ($data);
        break;
        Case ' 1_n ':
        {
            //one-to-many
            $data = usermodel::find (1)->artice ()->get ();
            DD ($data);
            break;
        Case ' n_1 ':
        {
            //multiple pairs of one
            $data = Usermodel::find (1)->country ()->get
            (); DD ($data);
            break;
        Case ' N_n ':
        {
            //many-to-many
           $data = Usermodel::find (2)->role ()->get
           (); DD ($data);
            break;
        default;
    }

}

Summarize:
1, one-to-one use:hasone ()
2, a One-to-many use method:hasmany ()
3, multiple to one use method:Belongsto ()
4. Multi-use Method:belongstomany ()

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.