laravel-模型关联查询的简单使用
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结果显示如下这里只演示角色表所包含的用户信息