TP5模型关联问题

在使用模型关联时:假如有表   merchant商户表   m_store 店铺表  m_store_ref 商户店铺关联表  user 普通用户表

$mer = Merchant::with([
       'MStoreRef',
       'MUserInfo',
       'MStoreRef.MStore',
 ])
     ->where('userid','=',$userid)
     ->find();
       

 返回的结果是如下数据 

{
    "status": 0,
    "error_code": 0,
    "msg": "获取成功",
    "info": {
        "id": 1,
        "userid": 1,
        "citycode": "",
        "parent_id": 0,
        "ctime": "2017-08-10 16:23:36",
        "money": "0.00",
        "name": "郑州秒秒信息科技",
        "type": 0,
        "license": "",
        "m_store_ref": {
            "userid": 1,
            "s_id": 1,
            "m_store": {
                "id": 1,
             
                "name": "秒秒总店",
                "userid": 1,
                "type": 1
            }
        },
        "m_user_info": {
            "id": 1,
            "username": "",
            "realname": "",
            "user_tel": "15136204782",
           
        }
    }
}

 现在要隐藏一些不需要返回的数据 

因为这里需要返回的数据只有指定的几个 所以这里使用 visible 来限制显示的字段 

 $mer->visible([
                'name',
                'm_store_ref',
                'm_user_info',
                'm_store_ref.m_store',
                'm_store_ref.m_store.name',
                'm_user_info.username',
                'm_user_info.user_tel',
            ]);


发现返回的结果 有些问题   在m_store 中的数据并没有按照想象的只获取name字段  
{
    "status": 0,
    "error_code": 0,
    "msg": "获取成功",
    "info": {
        "name": "郑州秒秒信息科技",
        "m_store_ref": {
            "m_store": {
                "id": 1,
              
                "name": "秒秒总店",
                "userid": 1,
                "type": 1
            }
        },
        "m_user_info": {
            "username": "",
            "user_tel": "15136204782"
        }
    }
}

尝试了很多写法后   发现这里 只可以限定到二级  如果有第三级参数 需要另行限制

 $mer->m_store_ref->m_store->visible(['name']);

 这样返回的结果就是最终想要返回的数据  

{
    "status": 0,
    "error_code": 0,
    "msg": "获取成功",
    "info": {
        "name": "郑州秒秒信息科技",
        "m_store_ref": {
            "m_store": {
                "name": "秒秒总店"
            }
        },
        "m_user_info": {
            "username": "",
            "user_tel": "15136204782"
        }
    }
}

 另外因为这里使用的hasone关联 所以直接使用hidden或者visible

如果关联的数据是多个也就是多对多关联 或者一对多关联时  查询获得的数组 想要使用hidden或者visible时 需要使用foreach 循环 来获取单个对象值  

再使用hidden或者visible

原文地址:https://www.cnblogs.com/wqy415/p/7380017.html