美文网首页
thinkphp5.1框架关联模型一对一查询,同时搜索基础表字段

thinkphp5.1框架关联模型一对一查询,同时搜索基础表字段

作者: 吴涛涛 | 来源:发表于2020-04-15 15:48 被阅读0次
描述:模型一对一关联查询,一次查询6张表数据,主表student_id关联基础表id,小学表student_id,初中表student_id,离校工作表student_id,离校学习表student_id,搜索条件有主表中字段,也有关联表中字段(我这边是基础表字段),可以用以下方法查询。

一.模型代码

class StudentSenior extends Model
{
    //关联基础表模型
    public function students(){
        return $this->belongsTo('Student', 'student_id', 'id');
    }
    //关联离校学习表模型
    public function study(){
        return $this->belongsTo('LeaveStudy', 'student_id', 'student_id');
    }
    //关联离校工作表模型
    public function work(){
        return $this->belongsTo('LeaveWork', 'student_id', 'student_id');
    }

    //关联小学表模型
    public function primary(){
        return $this->belongsTo('StudentPrimary', 'student_id', 'student_id');
    }
    //关联初中表模型
    public function junior(){
        return $this->belongsTo('StudentJunior', 'student_id', 'student_id');
    }
}

二.控制器代码

1.grade_id,classes_id两个字段在主表中(senior模型)
2.idcard,name两个字段在关联表student中(student模型)
3.最重要的:我尝试了很多次,最后总结出结果,with()方法和where()一定要放后面,hasWhere()方法一定要放前面,否则报错。
public function student_all(Request $request)
    {
        //搜索条件
        $where = [];
        $hasWhere = [];
        //年级
        if (isset($_GET['grade_name'])) {
            $where['grade_id'] = $_GET['grade_name'];
        }
        //班级
        if (isset($_GET['classes_name'])) {
            $where['classes_id'] = $_GET['classes_name'];
        }     
        //身份证
        if (isset($_GET['idcard'])) {
            $hasWhere['idcard'] = $_GET['idcard'];
        }
        //姓名
        if (isset($_GET['name'])) {
            $hasWhere['name'] = $_GET['name'];
        }
        //去空
        $where = array_filter($where);
        //关联查询小学,初中,高中,离校学习,离校工作表
        $data = SeniorModel::hasWhere('students',$hasWhere)->with('students,primary,junior,study,work')->where($where)->paginate(10);
        return json_encode($data);
    }

相关文章

网友评论

      本文标题:thinkphp5.1框架关联模型一对一查询,同时搜索基础表字段

      本文链接:https://www.haomeiwen.com/subject/dcvcvhtx.html