• 模型层关联


    以一对一为例,先说一下with如何使用

    一、最简单的,直接model->with('details')->get();

    只要在对应的model写上details方法

    public function details()
    {
        return $this->hasOne('App\Models\Admin\Business','id');
    }

     这个表示当前model表数据每条的business_id对应Business表的id,即一对一的关系

    二、如何用with带条件筛选呢 或者指定关联查询的字段呢

    有两种方式,根据自己的需求选择

    1. 不影响主表查询条数,只筛选关联表的查询结果

    1. $list = $this->ServiceModel->where($where)->with(['business' => function ($query) use ($name,$phone) {
    2. $where = [];
    3. if(!empty($name)){
    4. $where['name'] = $name;
    5. }
    6. if(!empty($phone)){
    7. $where['phone'] = $phone;
    8. }
    9. $query->where($where);
    10. $query->select('id', 'name', 'phone');
    11. }])->paginate($this->pageSize, ['*'], 'page', $page);

    以上查询结果:列表总条数不变,但不满足条件的查询出来的business为null

    如图所示

     

     

    2. 可作为搜索,只查询满足条件的条数,不满足条件的关联主表也不查询出来

    1. $query = $this->ServiceModel->where($where);
    2. $query->with(['business' => function($query1){
    3. $query1->select('id', 'name', 'phone');
    4. }]);
    5. $query->whereHas('business', function (Builder $query2) use ($name,$phone) {
    6. $where = [];
    7. if(!empty($name)){
    8. $where['name'] = $name;
    9. }
    10. if(!empty($phone)){
    11. $where['phone'] = $phone;
    12. }
    13. $query2->where($where);
    14. });
    15. $list = $query->paginate($this->pageSize, ['*'], 'page', $page);

    上面结果如图所示

     

  • 相关阅读:
    C++string—常用接口介绍+模拟实现+习题讲解
    List集合&UML图
    如何禁止公司电脑文件上传到网络
    HTML5 新元素之 canvas
    封装vue组件
    temp7777
    CentOS用nginx搭建文件下载服务器
    Anaconda下载和安装
    python的request库使用
    交换机和路由器技术-31-扩展ACL
  • 原文地址:https://blog.csdn.net/weixin_44052462/article/details/126498636