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 分享