1.模型1對多
先看一下表的結構
teacher表

CREATE TABLE `teacher` ( `id` int(255) NOT NULL, `name` varchar(255) DEFAULT NULL, `sex` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
student表(這里定義一個外鍵t_id)

CREATE TABLE `student` ( `id` int(11) NOT NULL, `name` varchar(255) DEFAULT NULL, `sex` varchar(255) DEFAULT NULL, `number` int(11) DEFAULT NULL, `t_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
1.2在App\Models中定義兩個模型1.Teacher.php 2.student.php
teacher模型

<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Teacher extends Model { // public $table='teacher'; public function haManyStudent(){ // return $this->hasMany('App\Models\Student','t_id','id');//這兩種方法都是一樣的使用 return $this->hasMany(Student::class,'t_id','id');//這兩種方法都是一樣的使用 } }
student模型

<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Student extends Model { // public $table='student'; }
1.3控制器中調模型

<?php namespace App\Http\Controllers; use App\Models\Teacher; class DemoController extends Controller { // public function demo() { $data=Teacher::with('haManyStudent')->get(); return response()->json($data);//轉化為json數據 } }
1.4 傳輸過來的模型在json中解析結果如下
2.多對多
2.1這里建立三張表一張角色表(roles),一張用戶表(users),一張外鍵表(role_user)
2.2 數據表結構

CREATE TABLE `roles` ( `id` int(11) NOT NULL, `name` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='角色表'; CREATE TABLE `users` ( `id` int(20) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用戶表'; CREATE TABLE `role_user` ( `user_id` int(11) DEFAULT NULL, `role_id` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='用戶角色外鍵表';
2.3模型類(第二個參數是關聯的外鍵表)

<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class User extends Model { // public $table='users'; protected $fillable=['name']; public function roles(){ return $this->belongsToMany(Role::class,'role_user','user_id'); } }

<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Role extends Model { // protected $table='roles'; protected $fillable=['name']; public function User(){ return $this->belongsToMany(User::class,'role_user','role_id'); } }
2.4控制器中代碼

public function index(){ // $data=User::with('roles')->get();//打印用戶表信息 $data=Role::with('User')->get();//打印角色表信息 return response()->json($data); }
2.5結果顯示如下這里只演示角色表所包含的用戶信息