thinkphp多对多关联

本案例:多个学生对多个课程
  • 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);
   }
}

本案例指导老师:刘老师

发布了122 篇原创文章 · 获赞 5 · 访问量 4797

猜你喜欢

转载自blog.csdn.net/weixin_41254345/article/details/104651503
今日推荐