search
HomePHP FrameworkLaravelLaravel introductory tutorial: The relationship between tables
Laravel introductory tutorial: The relationship between tablesNov 20, 2019 pm 04:51 PM
laravelGetting Started Tutorialrelationsurface

Laravel introductory tutorial: The relationship between tables

##First of all, about the relationship between tables

1.One-to-one

2.One-to-many

3.Many-to-one

4.Many-to-many

Distinguish between parent table and child table

1. The "one" side is the parent table

2. The "many" side It is a child table

How to deal with one-to-many relationships

Create a field (foreign key) in the child table to point to the parent table

How to deal with many-to-many relationships

Create an intermediate table to convert the "many-to-many" relationship into "one-to-many"

Case analysis

Table 1: User table (it_user)

Table 2: User details table (it_user_info)

Table 3: Article table (it_article)

Table 4: Country table (it_country)

Table 5: User role table (it_role)

① One-to-one

The user table (Table 1) and the details table (Table 2) have a one-to-one relationship

②One-to-many

The user table (Table 1) and the article table ( Table 3) is a one-to-many relationship

③Many-to-one

The user table (Table 1) and the country table (Table 4) are a many-to-one relationship

④Many-to-many

The user table (Table 1) and the role table (Table 5) are a many-to-many relationship

User table creation and test data

DROP TABLE IF EXISTS `it_user`;
CREATE TABLE `it_user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  `name` varchar(64) DEFAULT NULL COMMENT '用户名',
  `password` char(32) DEFAULT NULL COMMENT '密码(不使用md5)',
  `country_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `国家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 details table creation and test data

-- ----------------------------
-- Table structure for it_user_info
-- ----------------------------
DROP TABLE IF EXISTS `it_user_info`;
CREATE TABLE `it_user_info` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `tel` char(11) 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', '北京');
INSERT INTO `it_user_info` VALUES ('2', '15923456789', 'xiaomei@163.com', '上海');
INSERT INTO `it_user_info` VALUES ('3', '18973245670', 'xiaoli@163.com', '武汉');

Article table creation and test data

-- ----------------------------
-- Table structure for it_article
-- ----------------------------
DROP TABLE IF EXISTS `it_article`;
CREATE TABLE `it_article` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) DEFAULT NULL,
  `content` text,
  `user_id` int(11) 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', '世界那么大,我想去看看', '钱包那么小,总是不够', '1');
INSERT INTO `it_article` VALUES ('2', '我想撞角遇到爱', '却是碰到鬼', '2');
INSERT INTO `it_article` VALUES ('3', '哈哈哈哈', '嘻嘻嘻嘻', '1');

Country Table creation and test data

-- ----------------------------
-- Table structure for it_country
-- ----------------------------
DROP TABLE IF EXISTS `it_country`;
CREATE TABLE `it_country` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of it_country
-- ----------------------------
INSERT INTO `it_country` VALUES ('1', '中国');
INSERT INTO `it_country` VALUES ('2', '美国');

User role table creation and test data

-- ----------------------------
-- Table structure for it_role
-- ----------------------------
DROP TABLE IF EXISTS `it_role`;
CREATE TABLE `it_role` (
  `id` int(11) 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', '开发');
INSERT INTO `it_role` VALUES ('2', '测试');
INSERT INTO `it_role` VALUES ('3', '管理');

User and role intermediate table creation and testing Data

-- ----------------------------
-- Table structure for it_user_role
-- ----------------------------
DROP TABLE IF EXISTS `it_user_role`;
CREATE TABLE `it_user_role` (
  `user_id` int(11) DEFAULT NULL,
  `role_id` int(11) 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');

Preparation work

1. Planning routing

In routes/ Write the following route under web.php:

//ORM的关联关系
Route::get('/orm/relation/{mode}','ORM\UserController@relation');

2. Write the relation method in App/Http/Controllers/ORM/UserController.php

    public function relation($mode)
    {
        switch ($mode){
            case '1_1':
            {
                //一对一
            }
            break;
            case '1_n':
            {
                //一对多
            }
                break;
            case 'n_1':
            {
                //多对一
            }
                break;
            case 'n_n':
            {
                //多对多
            }
                break;
            default;
        }
    }

3. Install the debug debugging tool

3.1 Use the composer command to install

composer require  barryvdh/laravel-debugbar

3.2. Modify the config/app.php file, load debugbar to laravel into the project, and add it to the 'providers' array The following configuration:

Barryvdh\Debugbar\ServiceProvider::class,

In addition to installing the debugbar debugging tool, you can also use query monitoring: Add the following code to the boot method of providers/AppServiceProvider.php

\DB::listen(function ($query) {
    var_dump($query->sql);
     var_dump($query->bindings);
     echo &#39;<br>&#39;;
 });

You can also print out the executed sql statement.

One-on-one

1. Create the Userinfo model object

Enter the cmd command line. Executing the following command in the directory where the laravel project is located

php artisan make:model Userinfo

will generate Userinfo.php in the App directory

2. Edit the Userinfo model file

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Userinfo extends Model
{
    protected $table  =  &#39;user_info&#39;;
    protected $primaryKey = &#39;user_id&#39;;
    protected $fillable = [&#39;user_id&#39;,&#39;tel&#39;,&#39;email&#39;,&#39;addr&#39;];
    public    $timestamps = false;
}

3. Write UserModel and add one-to-one method

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserModel extends Model
{
    protected $table = &#39;user&#39;;//真是表名
    protected $primaryKey = &#39;id&#39;;//主键字段,默认为id
    protected $fillable = [&#39;name&#39;,&#39;password&#39;];//可以操作的字段
    public $timestamps = false;//如果数据表中没有created_at和updated_id字段,则$timestamps则可以不设置,
    默认为true
    public function Userinfo()
    {
        /*
         * @param [string] [name] [需要关联的模型类名]
         * @param [string] [foreign] [参数一指定数据表中的字段]
         * */
        return $this->hasOne(&#39;App\Userinfo&#39;,&#39;user_id&#39;);
    }

4. Write UserController and call one-to-one method

    public function relation($mode)
    {
        switch ($mode){
            case &#39;1_1&#39;:
            {
                //一对一
                $data = UserModel::find(1)->Userinfo()->get();
                dd($data);
            }
            break;
            default;
        }
    }

One-to-many

1. Create the article model object

Execute the command

php artisan make:model Article

Generate the Article.php file under the app

2. Write article model file

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
    protected $table = &#39;article&#39;;
    protected $primaryKey = &#39;id&#39;;
    protected $fillable = [&#39;id&#39;,&#39;title&#39;,&#39;content&#39;,&#39;user_id&#39;];
    public $timestamps  = false;
}

3. Write UserModel and add one-to-many method

public function Artice()
    {
        return $this->hasMany(&#39;App\Article&#39;,&#39;User_id&#39;);
    }

4. Write UserController and call one-to-many method

    public function relation($mode)
    {
        switch ($mode){
            case &#39;1_1&#39;:
            {
                //一对一
                $data = UserModel::find(1)->Userinfo()->get();
                dd($data);
            }
            break;
            case &#39;1_n&#39;:
            {
                //一对多
                $data = UserModel::find(1)->Artice()->get();
                dd($data);
            }
                break;
            default;
        }
    }
}

many-to-one

1. Create country model Object

executes the command

php artisan make:model Country

2. Write the country model file

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
    protected $table = &#39;country&#39;;   //真实表名
    protected $primaryKey = "id";   //主键id
    protected $fillable = [&#39;id&#39;,&#39;name&#39;];    //允许操作的字段
    public $timestamps = false; //如果数据表中没有created_at和updated_id字段,则$timestamps则可以不设置,
    默认为true
}

3. Write the UserModel and add many-to-one Method

public function Country()
{
    return $this->belongsTo(&#39;App\Country&#39;,&#39;country_id&#39;);
}

4. Write UserController and call method

public function relation($mode)
    {
        switch ($mode){
            case &#39;1_1&#39;:
            {
                //一对一
                $data = UserModel::find(1)->Userinfo()->get();
                dd($data);
            }
            break;
            case &#39;1_n&#39;:
            {
                //一对多
                $data = UserModel::find(1)->Artice()->get();
                dd($data);
            }
                break;
            case &#39;n_1&#39;:
            {
                //多对一
                $data = UserModel::find(1)->Country()->get();
                dd($data);
            }
                break;
            default;
        }
    }
}

Many-to-Many

1. Create role model object

Execute command

php artisan make:model Role

Execute command

php artisan make:model User_role

2.Write Role model

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
    protected $table = &#39;role&#39;;
    protected $primaryKey = "id";
    protected $fillable = [&#39;name&#39;];
    public $timestamps  =false;
}

Write the User_role model

Because there is no primary key field in the table, two fields are needed

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User_role extends Model
{
    protected $table = &#39;user_role&#39;;
    public $timestamps  =false;
}

3. Write the UserModel and add the many-to-many method

    public function Role(){
        /*
         * 第一个参数:要关联的表对应的类
         * 第二个参数:中间表的表名
         * 第三个参数:当前表跟中间表对应的外键
         * 第四个参数:要关联的表跟中间表对应的外键
         * */
        return $this->belongsToMany(&#39;App\Role&#39;,&#39;user_role&#39;,&#39;user_id&#39;,&#39;role_id&#39;);
    }

4. Write UserController and call the many-to-many method

public function relation($mode)
{
    switch ($mode){
        case &#39;1_1&#39;:
        {
            //一对一
            $data = UserModel::find(1)->Userinfo()->get();
            dd($data);
        }
        break;
        case &#39;1_n&#39;:
        {
            //一对多
            $data = UserModel::find(1)->Artice()->get();
            dd($data);
        }
            break;
        case &#39;n_1&#39;:
        {
            //多对一
            $data = UserModel::find(1)->Country()->get();
            dd($data);
        }
            break;
        case &#39;n_n&#39;:
        {
            //多对多
           $data = UserModel::find(2)->Role()->get();
           dd($data);
        }
            break;
        default;
    }
}

Summary:

1. One pair One usage method: hasOne()

2. One-to-many usage method: hasMany()

3. Many-to-one usage method: belongsTo()

4. Many How to use many: belongsToMany()

PHP Chinese website, a large number of free

laravel introductory tutorials, welcome to learn online!

This article is reproduced from: https://blog.csdn.net/weixin_38112233/article/details/79220535

The above is the detailed content of Laravel introductory tutorial: The relationship between tables. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
laravel单点登录方法详解laravel单点登录方法详解Jun 15, 2022 am 11:45 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于单点登录的相关问题,单点登录是指在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统,下面一起来看一下,希望对大家有帮助。

一起来聊聊Laravel的生命周期一起来聊聊Laravel的生命周期Apr 25, 2022 pm 12:04 PM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于Laravel的生命周期相关问题,Laravel 的生命周期从public\index.php开始,从public\index.php结束,希望对大家有帮助。

laravel中guard是什么laravel中guard是什么Jun 02, 2022 pm 05:54 PM

在laravel中,guard是一个用于用户认证的插件;guard的作用就是处理认证判断每一个请求,从数据库中读取数据和用户输入的对比,调用是否登录过或者允许通过的,并且Guard能非常灵活的构建一套自己的认证体系。

laravel中asset()方法怎么用laravel中asset()方法怎么用Jun 02, 2022 pm 04:55 PM

laravel中asset()方法的用法:1、用于引入静态文件,语法为“src="{{asset(‘需要引入的文件路径’)}}"”;2、用于给当前请求的scheme前端资源生成一个url,语法为“$url = asset('前端资源')”。

实例详解laravel使用中间件记录用户请求日志实例详解laravel使用中间件记录用户请求日志Apr 26, 2022 am 11:53 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于使用中间件记录用户请求日志的相关问题,包括了创建中间件、注册中间件、记录用户访问等等内容,下面一起来看一下,希望对大家有帮助。

laravel中间件基础详解laravel中间件基础详解May 18, 2022 am 11:46 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于中间件的相关问题,包括了什么是中间件、自定义中间件等等,中间件为过滤进入应用的 HTTP 请求提供了一套便利的机制,下面一起来看一下,希望对大家有帮助。

laravel路由文件在哪个目录里laravel路由文件在哪个目录里Apr 28, 2022 pm 01:07 PM

laravel路由文件在“routes”目录里。Laravel中所有的路由文件定义在routes目录下,它里面的内容会自动被框架加载;该目录下默认有四个路由文件用于给不同的入口使用:web.php、api.php、console.php等。

laravel的fill方法怎么用laravel的fill方法怎么用Jun 06, 2022 pm 03:33 PM

在laravel中,fill方法是一个给Eloquent实例赋值属性的方法,该方法可以理解为用于过滤前端传输过来的与模型中对应的多余字段;当调用该方法时,会先去检测当前Model的状态,根据fillable数组的设置,Model会处于不同的状态。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.