使用外键从 table 获取值

get values from table with foreign key

嗨,我有 2 个 tables 和模型。首先是

User

第二个

News

我想从table News 中获取用户id 并绘制她的名字和姓氏。有 table News:

的打印屏幕

我正在尝试使用以下功能:

public function getUrUser()
{
    $q= News::find()->where(['urUser_Id' =>'Id'])->one();
    $RoyalUserData=User::findOne($q);
    //$RoyalUserData= User::find()->where(['Id' => $q])->one();
    return $RoyalUserData->Name;
}

但这不起作用。只有当我为 egzample 规定 q 值为 3 时,它才会起作用。我知道这可能是我函数第一行中的错误代码。我知道这很容易,但我是初学者,我已经为代码奋斗了大约 1 小时。谁能帮帮我?

在我看来我使用这个:

<?=$model->getUrUser();?>

我在 ListView 中使用它。

我的控制器:

public function actionIndex()
    {
        $model = new NewsForm();
        $searchModel = new NewsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->setSort(['defaultOrder' => ['Id'=>SORT_DESC]]);

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $model->saveNews();
            return $this->redirect(['/content/news']);
        } else {
            return $this->render('index', [
                        'model' => $model,
                        'searchModel' => $searchModel,
                        'dataProvider' => $dataProvider,
            ]);
        }
    }

我使用 _item 的索引:

echo ListView::widget( [
    'dataProvider' => $dataProvider,
    'itemView' => '_item',
],  $options = ['class' => 'sorter'] ); ?>

以及_item的内容

<?php
use yii\helpers\Html;
?>  


Treść Newsa:
<?=$model->Text;?> <br>
Autor:
<?=Yii::$app->user->identity->Name?> 
<?=Yii::$app->user->identity->Surname?> <br>
Status Newsa:
<?=$model->cnNewsContentType_Id;?> <br>

  <?= Html::a('Update', ['update', 'id' => $model->Id], ['class' => 'btn btn-primary']) ?>
        <?= Html::a('Delete', ['delete', 'id' => $model->Id], [
            'class' => 'btn btn-danger',
            'data' => [
                'confirm' => 'Are you sure you want to delete this item?',
                'method' => 'post',
            ],
        ]) ?><br><br><br>
public function getUrUser()
{
    $q = News::find()->where(['urUser_Id' =>'Id'])->one();
    return $q->user->name;
}

在用户模型中你应该创建 relation:

class News extends ActiveRecord
{
    // ...

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

News::find()->where(['urUser_Id' =>'Id'])->one() return 模型不是字段

那么你必须通过模型这样获取id字段

public function getUrUser($id)
{
    // you already have the news model so don't need retrieve it 
    //  it's enough pass the urUser_Id by $id

    $RoyalUserData=User::findOne($id);

    return $RoyalUserData->Name;
}

那么如果你想在 _item 中显示 ($RoyalUserData) 名称

<?=$model->getUrUser($model->urUser_Id);?>