フォロワー 3

複数のモデルのデータ取得

複雑なデータを扱う場合、ユーザー入力の収集に複数の異なるモデルを使用する必要があるかもしれません。例えば、ユーザーログイン情報がuserテーブルに格納され、ユーザープロフィール情報がprofileテーブルに格納されていると仮定すると、UserモデルとProfileモデルを通じてユーザーに関する入力データを収集したい場合があります。Yiiのモデルとフォームのサポートにより、単一のモデルを扱う場合とそれほど変わらない方法でこの問題を解決できます。

以下では、UserモデルとProfileモデルの両方のデータを収集できるフォームを作成する方法を示します。

まず、ユーザーとプロファイルのデータを収集するためのコントローラーアクションは、次のように記述できます。

namespace app\controllers;

use Yii;
use yii\base\Model;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use app\models\User;
use app\models\Profile;

class UserController extends Controller
{
    public function actionUpdate($id)
    {
        $user = User::findOne($id);
        if (!$user) {
            throw new NotFoundHttpException("The user was not found.");
        }
        
        $profile = Profile::findOne($user->profile_id);
        
        if (!$profile) {
            throw new NotFoundHttpException("The user has no profile.");
        }
        
        $user->scenario = 'update';
        $profile->scenario = 'update';
        
        if ($user->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post())) {
            $isValid = $user->validate();
            $isValid = $profile->validate() && $isValid;
            if ($isValid) {
                $user->save(false);
                $profile->save(false);
                return $this->redirect(['user/view', 'id' => $id]);
            }
        }
        
        return $this->render('update', [
            'user' => $user,
            'profile' => $profile,
        ]);
    }
}

updateアクションでは、まずデータベースから更新対象の$userモデルと$profileモデルを読み込みます。次に、yii\base\Model::load()を呼び出して、これらの2つのモデルにユーザー入力を設定します。読み込みが成功した場合、2つのモデルを検証してから保存します。 — save(false)を使用して、ユーザー入力データが既に検証済みであるため、モデル内の検証をスキップすることに注意してください。読み込みが成功しなかった場合は、次の内容のupdateビューをレンダリングします。

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;

$form = ActiveForm::begin([
    'id' => 'user-update-form',
    'options' => ['class' => 'form-horizontal'],
]) ?>
    <?= $form->field($user, 'username') ?>

    ...other input fields...
    
    <?= $form->field($profile, 'website') ?>

    <?= Html::submitButton('Update', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end() ?>

ご覧のとおり、update ビューでは、$user$profile の2つのモデルを使用して入力フィールドをレンダリングします。

誤字を見つけましたか?または、このページの改善が必要だと思いますか?
GitHub で編集する !