這篇文章主要介紹了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}','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()
感謝你能夠認真閱讀完這篇文章,希望小編分享的“laravel中表與表之間的關系是什么”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。