Yii2 显示不在数组中的相关数据,不使用 Listview 或 Gridview

Yii2 Display Related Data not in Array, not using Listview or Gridview

我有一个名为 Dashboard.php 的主视图,我想在其中显示已登录员工的单元格 phone(来自存储所有员工 employee_phone table =50=] 个数字,并在视图上标记为 'phone 1:' 的任意字段中按 'phone_type'(即单元格、家庭、主))区分,然后显示它们的 'home' 或 'main' 数为 'phone 2:'。请注意,为清楚起见,我省略了 'home' phone 提供程序,因为我确信如果有人可以帮助 'cell' phone 类型,我可以弄清楚。我无法显示任何 phone 数字,我已经尝试了几种配置。感谢您的帮助,我提前为我的新鲜事道歉。我已阅读此页面:http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#querying-data,它似乎符合我的标准,但我就是无法让它发挥作用。我还在此处阅读了有关 SO 的相关问题,但它们似乎与处理数组中的数据并将其显示在 ListView 或 Gridview 中有关。我似乎也无法让提供者能够使用 employeeCellPhone 的魔术方法访问方法 getEmployeeCellPhone()。

我有两个 table:

员工Table:
编号
user_id

employee_phone Table:
编号
employee_id
phone_number
phone_type

Employee.php 型号:

public function getEmployeePhones()
{
    return $this->hasMany(\frontend\models\EmployeePhone::className(), ['employee_id' => 'id']);
}

public function getEmployeeCellPhone()
{
    return $this->hasOne(\frontend\models\EmployeePhone::className(), ['employee_id' => 'id'])
        ->where(['=', 'phone_type', 'Cell'])
        ->all();
}

雇员控制器:

public function actionDashboard($id)
{
    $model = $this->findModel($id);

    $providerCellPhone = $model->employeeCellPhone;
    return $this->render('dashboard', [
        'model' => $this->findModel($id),
        'providerCellPhone' => $providerCellPhone,
    ]);
}

Dashboard.php 查看:

<div class="col-lg-3">
            Phone 1: <?= $model->$providerCellPhone ?><br>
            Phone 2: <?= $model->$providerHomePhone ?>

        </div>

请尝试以下方法检查您的问题是否已解决 -

//EmployeeController
public function actionDashboard($id)
{
    $model = $this->findModel($id);

    return $this->render('dashboard', [
        'model' => $model,
    ]);
}

以及查看文件-

//Dashboard.php View
<div class="col-lg-3">
    Phone 1: <?= $model->employeeCellPhone[0]->phone_number  ?><br>
    Phone 2: <?= $model->employeeHomePhone[0]->phone_number  ?>
</div>

要正确输出值 $model->employeeCellPhone[0] 是必需的,因为在您的 getEmployeeCellPhone() 函数中,您使用了 ->all() 函数。编写仪表板代码时假设在数据库中每个 phone_type 每个用户只存在一个 phone 号码。如果不是这种情况,您需要在视图中遍历 $model->employeeCellPhone 并获得所需的输出。

此外,您上面粘贴的模型代码没有显示 getEmployeeHomePhone() 函数,我假设您有它。