YII2 如何获取具有hasMany 关系的多级关系中的数据

时间:2021-02-08 09:59:13

标签: php yii2

我有 3 张桌子:

网络、公司、部门

网络

<头>
id 姓名
1 网络1
2 网络2

公司

<头>
id network_id 姓名
1 1 公司 1
2 1 公司 2

部门

<头>
id company_id 姓名
1 1 Dep 1
2 1 Dep 2
3 2 Dep 3
4 2 Dep 4

我有 ActiveRecord 关系

在网络模型中

public function getCompany()
    {
        return $this->hasMany(Company::className(), ['network_id' => 'id']);
    }

在公司模型中

public function getDepartment()
    {
        return $this->hasMany(Department::className(), ['company_id' => 'id']);
    }

我需要从网络模型中的 Network id = 1 中获取所有部门。

1 个答案:

答案 0 :(得分:0)

你可以这样称呼它:

RemoteMessage.Notification notification = remoteMessage.getNotification();
        Map<String, String> data = remoteMessage.getData();
        sendNotification(notification, data);
String urlparam=data.get("url_param").toString();
String urlparam=data.get("dp_name").toString();

"data": {
    "notification_id": 11,
    "title_url": "service_id=1;service_category=Installation;",
    "destination": "Category_page"
  }

还有你的 foreach:

$results = Network::find()
    ->joinWith('company')
    ->joinWith('company.department')
    ->where(['network.id' => 1])
    ->all();

其他方式,我认为更好

if($results){
    foreach($results as $result){
        if($companies = $result->company){ 
            foreach($companies as $company){ //foreach you companies attached to network One
                if($departments = $company->department){
                    foreach($departments as $department){ //foreach you departments attached to every company
                        echo $department->name.' (Company: '.$company->name.')';
                    }
                }
            }
        }
    }
}

这取决于你需要展示什么数据。

附注。在您的 $departments = Department::find() ->leftJoin('company', 'company.id = department.company_id') ->where('company.network_id = 1') ->all(); 中必须与 Department 有关系并且可以使用它

相关问题