我如何检索用户的名字? (yii2)

How do i retrieve user first name? (yii2)

抱歉,我是 yii2 的新手,我正在努力适应它:( 我真的只想显示我的用户的名字而不是他的 ID,并且由于 ID 在一个 table 中而名称在另一个中,所以我无法理解我必须做什么才能检索。这是我的数据库和代码:

我有 3 个 tables:

tbl_user_notification:

id(PK), comment

tbl_user_notification_用户:

id(PK), n_id (FK), user_id (FK)

tbl_user:

id(PK), first_name, last_name.

在通知的索引页面中,我想显示评论(来自 tbl_user_notification)以及通知发送到的用户的名字和姓氏(来自 tbl_user)。

不过,我只能设法在索引页上显示 ID。请问如何显示名字?

通知模型:

    public function getNotifUsers()
    {
        return $this->hasOne(NotificationsUsers::className(), ['n_id' => 'id']);
    }

我的通知索引页:

GridView::widget([
            'dataProvider' => $dataProvider,
            'filterModel' => $searchModel,
            'columns' => [
                ['class' => 'yii\grid\SerialColumn'],
                //'id',
                [
                    'label' => 'First Name',
                    'value' => 'notifUsers.user_id',
                ],
                'comments',
(etc)

我假设下面的连接函数在 UserNotification 模型中,而您正在将它连接到 UserNotificationUser 模型。

   public function getNotifUsers()
    {
        return $this->hasOne(NotificationsUsers::className(), ['n_id' => 'id']);
    }

现在您已经连接到 UserNotificationUser 模型,您需要将该模型连接到 User 模型,因为它具有 user_id.

解决方案:在 userNotificationUser 模型中,添加一个新函数:

   public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

然后在 Gridview 中,您只需按顺序调用连接 - 首先是 notifUser,然后是用户,然后是用户属性:

GridView::widget([
            'dataProvider' => $dataProvider,
            'filterModel' => $searchModel,
            'columns' => [
                ['class' => 'yii\grid\SerialColumn'],
                'notifUsers.user.first_name'
                // or
                [
                    'label' => 'First Name',
                    'value' => 'notifUsers.user.first_name',
                ],
                'comments',