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

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

首先关于表与表之间的关系

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}','ORMUserController@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’数组中加入如下配置:

BarryvdhDebugbarServiceProvider::class,

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

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

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

一对一

1、创建Userinfo模型对象

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

php artisan make:model Userinfo

会在App目录下生成Userinfo.php

2、编辑Userinfo模型文件

<?php namespace App; use IlluminateDatabaseEloquentModel; 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、编写UserModel, 加入一对一方法

<?php namespace App; use IlluminateDatabaseEloquentModel; 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('AppUserinfo','user_id');     }

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

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

一对多

1、创建article模型对象

执行命令

php artisan make:model Article

在app下生成Article.php文件

2、编写article模型文件

<?php namespace App; use IlluminateDatabaseEloquentModel; 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、编写UserModel, 加入一对多方法

public function Artice()     {         return $this-&gt;hasMany('AppArticle','User_id');     }

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

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

多对一

1、创建country模型对象

执行命令

php artisan make:model Country

2、编写country模型文件

<?php namespace App; use IlluminateDatabaseEloquentModel; 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、编写UserModel, 加入多对一方法

public function Country() {     return $this-&gt;belongsTo('AppCountry','country_id'); }

4、编写UserController, 调用方法

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

多对多

1、创建role模型对象

执行命令

php artisan make:model Role

执行命令

php artisan make:model User_role

2、编写Role模型

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

编写User_role模型

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

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

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

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

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

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

总结:

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

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

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

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

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

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

以上就是

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享