简体   繁体   中英

yii2 gii crud db relation(one to many)

gii generated models successfully (with relations) :

/**
 * @return \yii\db\ActiveQuery
 */
public function getClient()
{
    return $this->hasOne(Client::className(), ['id' => 'client_id']);
}

but when i generated crud, in client filed just input text field. Help me please, where is problem?

That's correct. In your _form.php file you have to define a dropdown box if the user should choose a client:

<?= $form->field($model, 'client')->dropDownList($clients) ?>

and in controller actions create/update you have to provide the $clients:

return $this->render('create', [  // or: return $this->render('update', [
    'model'    => $model,
    'clients' => ArrayHelper::map(Client::find()->all(), 'id', 'name'),
]);

Don't forget to pass them in the view files for create.php and update.php to the _form.php file:

<?= $this->render('_form', [
    'model' => $model,
    'clients' => $clients, // <-- added
]) ?>

In other views where you just want to show client you may use this:

echo $model->client->name; //or something different

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM