laravel入门教程之表与表之间的关系

2020-11-10,,,

/2020/11/5a7a57e1.jpg

首先关于与表之间的关系

1.一对一

2.一对多

3.多对一

4.多对多

区分父表与子表

1.”一”的是父表

2.”多”的一方是子表

如何处理一对多关系

在子表中建一个字段(外键)指向父表

如何处理多对多关系

建立一张中间表,将”多对多”关系转化为”一对多”

案例分析

表一: 用户表(it_user)

表二: 用户详情表(it_user_info)

表三: 文章表(it_article)

表四: 国家表(it_country)

表五: 用户角色表(it_role)

① 一对一

用户表(表一)与详情表(表二)就是一对一的关系

②一对多

用户表(表一)与文章表(表三)就是一对多的关系

③多对一

用户表(表一)与国家表(表四)就是多对一的关系

④多对多

用户表(表一)与角色表(表五)就是多对多的关系

用户表建表及测试数据

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');

用户详情表建表及测试数据

-- ----------------------------
-- 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', '武汉');

文章表建表及测试数据

-- ----------------------------
-- 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');

国家表建表及测试数据

-- ----------------------------
-- 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', '美国');

用户角色表建表及测试数据

-- ----------------------------
-- 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', '管理');

用户和角色中间表表建表及测试数据

-- ----------------------------
-- 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');

准备工作

1、规划路由

在routes/web.php下写如下路由:

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

2、在App/Http/Controllers/ORM/UserController.php编写relation方法

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

3、安装debug调试工具

3.1使用composer命令安装

composer require  barryvdh/laravel-debugbar

3.2、修改config/app.php文件,加载debugbar到laravel到项目中,在’providers’数组中加入如下配置:

Barryvdh\Debugbar\ServiceProvider::class,

除了安装debugbar调试工具外,也可以使用查询监听:编providers/AppServiceProvider.php的boot方法中加入如下代码

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

也可以打印出执行的sql语句。

一对一

1、创建Userinfo模型对象

进入cmd命令行进入laravel项目所在目录执行以下命令

php artisan make:model Userinfo

会在App目录下生成Userinfo.php

2、编辑Userinfo模型文件

<?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、编写UserModel, 加入一对一方法

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

4、编写UserController, 调用一对一方法

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

一对多

1、创建article模型对象

执行命令

php artisan make:model Article

在app下生成Article.php文件

2、编写article模型文件

<?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、编写UserModel, 加入一对多方法

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

4、编写UserController,调用一对多方法

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

多对一

1、创建country模型对象

执行命令

php artisan make:model Country

2、编写country模型文件

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

3、编写UserModel, 加入多对一方法

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

4、编写UserController, 调用方法

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

多对多

1、创建role模型对象

执行命令

php artisan make:model Role

执行命令

php artisan make:model User_role

2、编写Role模型

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

编写User_role模型

因为表中没有主键字段,所以需要两个字段即可

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

3、编写UserModel, 加入多对多方法

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

4、编写UserController, 调用多对多方法

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

总结:

1、一对一使用方法:hasOne()

2、一对多使用方法:hasMany()

3、多对一使用方法:belongsTo()

4、多对多使用方法:belongsToMany()

PHP中文网,大量的免费laravel入门教程,欢迎在线学习!

本文转自:https://blog.csdn.net/weixin_38112233/article/details/79220535

以上就是laravel入门教程之表与表之间的关系的详细内容,更多请关注北冥有鱼其它相关文章!

本文转载自【PHP中文网】,希望能给您带来帮助,苟日新、日日新、又日新,生命不息,学习不止。

《laravel入门教程之表与表之间的关系.doc》

下载本文的Word格式文档,以方便收藏与打印。