本案例:多个学生对多个课程
- student表
- classsheet表
- middle表,也就是中间表
- student模型
<?php
namespace app\my\model;
use think\Model;
class Student extends Model{
public function classsheet(){
return $this->belongsToMany('Classsheet','\\app\\my\\model\\Middle');
}
}
- classsheet模型
<?php
namespace app\my\model;
use think\Model;
class Classsheet extends Model{
public function student(){
return $this->belongsToMany('Student','\\app\\my\\model\\Middle');
}
}
- middle模型
<?php
namespace app\my\model;
use think\model\Pivot;
class Middle extends Pivot{
}
- 操作类
<?php
namespace app\my\controller;
use app\my\model\Student;
class Moretomore{
public function index(){//查
$student = Student::get(1);
$classsheet = $student->classsheet;
return json($classsheet);
}
public function add(){//增
$student = Student::get(1);
$res =$student->classsheet()->save(['name'=>'历史']);
return json($res);
}
public function addtomiddle(){//单独增加到中间表,前提是classsheet已有增加attach(3)中的3
$student = Student::get(2);
$res =$student->classsheet()->attach(3);
return json($res);
}
public function del(){//删
$student = Student::get(2);
$res =$student->classsheet()->detach([1,3]);
return json($res);
}
}
本案例指导老师:刘老师