1. 程式人生 > >[轉載]關於laravel中表關系的一對一、一對多、多對一、多對多實踐

[轉載]關於laravel中表關系的一對一、一對多、多對一、多對多實踐

對象 foreign 主鍵 fault pri create 密碼 names ace

這是轉載的文章

出處: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, [email protected], 北京);
INSERT INTO `it_user_info` VALUES (2, 15923456789, [email protected], 上海);
INSERT INTO `it_user_info` VALUES (3, 18973245670, [email protected], 武漢);

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\[email protected]‘);

三。編寫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中表關系的一對一、一對多、多對一、多對多實踐