首页 文章

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

提问于
浏览
0

我有一个名为Dashboard.php的主视图,其中我想显示一个登录的员工's cell phone (from the employee_phone table which stores all employee phone numbers and are differentiated by ' phone_type ' (ie cell, home, main)) in an arbitrary field labeled as ' phone 1:' on the view, then display either their ' home ' or ' main ' number as ' phone 2:'. Please note, for clarity I left out the ' home ' phone provider as I'我确定如果有人可以帮助'cell'我可以弄明白手机类型 . 我无法显示任何电话号码,而且我已经阅读了这个页面:http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#querying-data并且它似乎符合我的标准,但我也可以在这里阅读相关问题,但它们似乎与处理数组中的数据有关并在ListView或Gridview中显示它 . 我似乎也无法让提供者能够使用employeeCellPhone的魔术方法访问方法getEmployeeCellPhone() .

我有两张 table :

员工表:
ID
用户身份

employee_phone表:
ID
员工ID
电话号码
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();
}

EmployeeController:

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>

1 回答

  • 1

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

    //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() 函数 . 编写仪表板代码假设在DB中每个phone_type每个用户只存在一个电话号码 . 如果不是这种情况,则需要在视图中循环 $model->employeeCellPhone 并获得所需的输出 .

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

相关问题