其他分享
首页 > 其他分享> > [转载]关于laravel中表关系的一对一、一对多、多对一、多对多实践

[转载]关于laravel中表关系的一对一、一对多、多对一、多对多实践

作者:互联网

这是转载的文章

出处:https://blog.csdn.net/weixin_38112233/article/details/79220535

作者:重新遇到

一。建表和插入测试数据

1.用户表建表及测试数据

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;

插入测试数据

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

 

 

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

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;
插入测试数据

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

 

3文章表建表及测试数据

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;

插入测试数据

INSERT INTO `it_article` VALUES ('1', '世界那么大,我想去看看', '钱包那么小,总是不够', '1');
INSERT INTO `it_article` VALUES ('2', '我想撞角遇到爱', '却是碰到鬼', '2');
INSERT INTO `it_article` VALUES ('3', '哈哈哈哈', '嘻嘻嘻嘻', '1');

 

4.国家表建表及测试数据

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;

插入测试数据

INSERT INTO `it_country` VALUES ('1', '中国');
INSERT INTO `it_country` VALUES ('2', '美国');

 

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

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;

插入测试数据

INSERT INTO `it_role` VALUES ('1', '开发');
INSERT INTO `it_role` VALUES ('2', '测试');
INSERT INTO `it_role` VALUES ('3', '管理');

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

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;

插入测试数据

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

二设置表前缀
打开config/database.php
'prefix' => env('DB_PREFIX', ''),
 然后在.env文件中加入DB_PREFIX=it_

执行命令

php artisan make:controller ORM\UserController

<?php

namespace App\Http\Controllers\ORM;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    public function relation($mode)
    {
        switch ($mode){
            case '1_1':
                {
                    //一对一

                }
                break;
            case '1_n':
                {
                    //一对多

                }
                break;
            case 'n_1':
                {
                    //多对一

                }
                break;
            case 'n_n':
                {
                    //多对多

                }
                break;
            default;
        }

    }

}

 

php artisan make:model UserModel
Model created successfully.

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

}

php artisan make:model Userinfo
Model created successfully.

<?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;
}

添加路由

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

三。编写UserController, 调用一对一方法

<?php

namespace App\Http\Controllers\ORM;

use App\UserModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

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

                }
                break;
            case 'n_1':
                {
                    //多对一

                }
                break;
            case 'n_n':
                {
                    //多对多

                }
                break;
            default;
        }

    }

}

http://127.0.0.1/fun/public/orm/relation/1_1

php artisan make:model Article
Model created successfully.

编写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;

}

编写UserModel, 加入一对多方法

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

编写UserController,调用一对多方法

case '1_n':
{
    //一对多
    $data = UserModel::find(1)->Artice()->get();
    dd($data);

}
break;

http://127.0.0.1/fun/public/orm/relation/1_n

 

php artisan make:model Country
Model created successfully.

、编写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

}

 

编写UserModel, 加入多对一方法

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

编写UserController, 调用方法

case 'n_1':
{
//多对一
//多对一
$data = UserModel::find(1)->Country()->get();
dd($data);

}
break;

http://127.0.0.1/fun/public/orm/relation/n_1

1、创建role模型对象

执行命令 
php artisan make:model Role 
执行命令 
php artisan make:model User_role

2、编写Role模型

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, 调用多对多方法

case 'n_n':
{
    //多对多
    $data = UserModel::find(2)->Role()->get();
    dd($data);

}
break;

http://127.0.0.1/fun/public/orm/relation/n_n

标签:laravel,INSERT,一对一,INTO,中表,role,user,VALUES,id
来源: https://www.cnblogs.com/code1521/p/10778067.html