Yii2.0 一对多,多对多关联模型

作者:谢高升 发布:2016-03-05 浏览:1138次
//控制器
class DevinfoController extends Controller
{
    public  function actionIndex()
    {
    	//定义数组
       $data = [];
       $lists  = Aps::find()->with('building','square','square.locationid')->asArray()->all();
       if($lists){
           foreach ($lists as $key=> $list)
           {
               $data[$key]['dev_code'] = $list['building_id'];
               $data[$key]['dev_name'] = $list['building']['building_name'];
               $data[$key]['location_id'] = $list['square']['locationid']['location_id'];
               $data[$key]['ap_mac'] = $list['mac'];
           }
           //销毁其他数据
           unset($lists);
           
       }
       return json_encode($data);
    }
   }


建筑模型building.php

 public function getAps()
    {
        return $this->hasMany(Aps::className(), ['building_id'=>'id']);
    }

广场模型square.php

 /**
     * 关联地区表
     * @return \yii\db\ActiveQuery
     */
    public function getLocationid()
    {
        return $this->hasOne(SysLocationInfo::className(), ['location_id'=>'location_id']);
    }


感谢博主,喝杯咖啡~