ThinkPHP5 Model layer and multiple-to-Multiple Association creation, thinkphp5model
I recently started ThinkPHP5 and planned to use it to implement a student assignment management system. Simply put, students submit their assignments in the course assigned by the teacher. The teacher can also publish and modify assignments. The relationship between students, classes, and teachers is inevitable. The relationship between them is many-to-many. Next we will analyze the relationship between classes and assignments. Each class can have multiple assignments, and the same assignments can be assigned to different classes. Therefore, the relationship between classes and assignments is many-to-many. Class table (tb_clas), job table (tb_task), and intermediate table (tb_task_class ). The Model layer code is written below. The Model layer is subdivided into the logic layer, service layer, and Model layer (separating data from logic ).
The Model layer code is as follows:
1. Class (clas. php)
<?phpnamespace app\index\model;use think\Model;class Clas extends Model{public function task(){return $this->belongsToMany('Task','tb_task_clas');}}
2. Job (task. php)
<?phpnamespace app\index\model;use think\Model;class Task extends Model{public function clas(){return $this->belongsToMany('Clas','tb_task_clas');}}
In this way, the many-to-many relationship between the class and the job model is established. The following is a list of all assignments assigned to a student. This involves the student table tb_Student. We write this logic in the logic of the student model (separating data from processing)
3. Logic layer of the Student Model
<? Phpnamespace app \ index \ logic; use think \ Model; use app \ index \ model \ Clas; class Student extends Model {// obtain all the public function getTasks ($ stuno) of the Student's class {$ stu = $ this :: get (['stu _ no' => $ stuno]); $ clas = Clas :: get (['clas _ id' => $ stu ['clas _ id']); return $ clas-> task ;}}
In this way, after instantiating the logic in the controller, you can find the jobs that any student has to do. The code in the Controller is as follows:
$stulogic=\think\Loader::model('Student','logic');$stuno=$request->session('stuno');//dump($stulogic->getTasks($stuno));$tasklist=$stulogic->getTasks($stuno);//dump($tasklist);$this->assign('tasklist',$tasklist);
You can use a volist on the page:
{volist name="tasklist" id="task"} <li>
The above is a bit of experience I have shared with thinkphp5. If anything is inappropriate, please criticize and correct me!