如何修复'“frontend models model”必须在Yii2高级模板中有一个主键'错误

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何修复'“frontend models model”必须在Yii2高级模板中有一个主键'错误相关的知识,希望对你有一定的参考价值。

我正在尝试创建一个模型,显然所有过程都是正确的但当我尝试在视图中显示他的错误时(创建模型后立即)Yii2-app抛出

无效的配置 - yii \ base \ InvalidConfigException - “frontend \ models \ mystore \ Staff”必须有一个主键。

解决此问题的唯一方法(直到现在)是从本地服务器重启mysql服务并在浏览器上刷新页面,之后我的应用程序显示所有数据而没有错误,直到我创建新记录。

我正在使用XAMPP,就像我的本地服务器和MySQL一样的数据库管理系统,当我使用phpmyadmin搜索新记录时,一切正常,PK被创建并且所有数据都被正确存储。

模型


namespace frontend\models\mystore;

use Yii;
use frontend\models\basic\PersonalData;
use frontend\models\mystore\Charges;
use frontend\models\mystore\MyStore;
use common\models\User;


/**
 * This is the model class for table "staff".
 *
 * @property int $id
 * @property int $store_id
 * @property string $code 
 * @property int $personal_data_id
 * @property int $charge_id 
 * @property int $active
 * @property int $created_at
 * @property int $updated_at
 * @property int $visible
 * @property int $user_id
 *
 * @property SaleOrders $saleOrders
 * @property User $user
 * @property Charges $charge
 * @property MyStore $store
 * @property PersonalData $personalData
 */
class Staff extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'staff';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['store_id', 'personal_data_id', 'charge_id', 'active', 'created_at', 'updated_at', 'visible', 'user_id'], 'integer'],
            [['code'], 'string', 'max' => 15],
            [['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
            [['charge_id'], 'exist', 'skipOnError' => true, 'targetClass' => Charges::className(), 'targetAttribute' => ['charge_id' => 'id']],
            [['store_id'], 'exist', 'skipOnError' => true, 'targetClass' => MyStore::className(), 'targetAttribute' => ['store_id' => 'id']],
            [['personal_data_id'], 'exist', 'skipOnError' => true, 'targetClass' => PersonalData::className(), 'targetAttribute' => ['personal_data_id' => 'id']],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'store_id' => 'Store ID',
            'code' => 'Code',
            'personal_data_id' => 'Personal Data ID',
            'charge_id' => 'Charge ID',
            'active' => 'Active',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
            'visible' => 'Visible',
            'user_id' => 'User ID',
        ];
    }

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

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

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

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

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

调节器

/**
 * Creates a new Staff model.
 * If creation is successful, the browser will be redirected to the 'index' page.
 * @return mixed
 */
public function actionCreate()
{
    $transaction = \Yii::$app->db->beginTransaction();

    try{
        $staffModel = new Staff();
        $isValid = false;

        $personalDataModels = $this->processPersonalData();// create, load and save personal information, return array with models
        $signupModel = $this->signup(); // create new account
        $personal_data_id = $personalDataModels['persDataModel']->getPrimaryKey(); // get PK when model is stored, get model if not

        if( $personal_data_id && is_int($signupModel) ){ // personal data && user saved correctly

            $staffModel->load(Yii::$app->request->post()); // the only field to be loaded is "code" who is not required

            $staffModel->setAttributes(['store_id' => Yii::$app->user->identity->store, 'personal_data_id' => $personal_data_id, 'active' => 1, 'user_id' => $signupModel ]); // populate the staff model

            $isValid = $staffModel->save();

            if(!$isValid){ // model is not valid
                $transaction->rollBack();
            }
        }

        if($isValid){
            $transaction->commit();

            return $this->redirect(['index']);
        }

        $chargesList = Charges::find()->select(['id', 'name'])->asArray()->all();

        return $this->render('create', [
            'staffModel' => $staffModel,
            'chargesList' => $chargesList,
            'signupModel' => $signupModel,
            'personalModels' => $personalDataModels,
        ]);

    } catch(\Exception $e) {
        $transaction->rollBack();
        throw $e;
    } catch(Exception $e) {
        $transaction->rollback();
    }
}

视图


use yii\helpers\html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel frontend\models\mystore\StaffSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Staff';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="staff-index">

    <h1><?= Html::encode($this->title) ?></h1>

    <p>
        <?= Html::a('Create Staff', ['create'], ['class' => 'btn btn-success']) ?>
    </p>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            'code',
            [
                'attribute' => 'name', // public property on searchModel
                'label' => 'Nombre',
                'value' => 'personalData.first_name'// method relation name on main Model . field name
            ],
            [
                'attribute' => 'last_name',
                'label' => 'Apellido',
                'value' => 'personalData.first_last_name'
            ],
            [
                'attribute' => 'charge',
                'label' => 'Cargo',
                'value' => 'charge.name'
            ],
            [
                'attribute' => 'username',
                'label' => 'Nombre de Usuario',
                'value' => 'user.username'
            ],
            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
</div>

创建Staff模型后,我希望浏览器重定向到索引页面,所有信息都可以在gridview中显示,但是我得到了上面提到的错误。

接下来是完整的错误消息:

"Invalid Configuration – yii\base\InvalidConfigException
Primary key of 'frontend\models\mystore\Staff' can not be empty."

in C:\xampp\htdocs\myapp\vendor\yiisoft\yii2\db\ActiveQuery.php
  }
                $key = serialize($key);
                if (isset($hash[$key])) {
                    unset($models[$i]);
                } else {
                    $hash[$key] = true;
                }
            }
        } elseif (empty($pks)) {
            throw new InvalidConfigException("Primary key of '{$class}' can not be empty.");
        } else {
            // single column primary key
            $pk = reset($pks);
            foreach ($models as $i => $model) {
                if (!isset($model[$pk])) {
                    // do not continue if the primary key is not part of the result set
                    break;
                }
                $key = $model[$pk];
答案

似乎你的模型中没有主键(可能在你的表中)

您可以通过这种方式手动将主键字段添加到模型中 作为公共静态方法

  class Staff extends \yii\db\ActiveRecord
  {

      /**
       * {@inheritdoc}
       */
      public static function tableName()
      {
          return 'staff';
      }

     /**
       * @inheritdoc$primaryKey
       */
      public static function primaryKey()
      {
          return ["your_id_column"];
      }

   ........

以上是关于如何修复'“frontend models model”必须在Yii2高级模板中有一个主键'错误的主要内容,如果未能解决你的问题,请参考以下文章

如何修复mscorlib.dll中发生的''System.AggregateException'“

joomla:如何修复“CLASS'JPLATFORMUTILITY'未找到”

如何修复'ERROR TypeError:Object(...)不是函数'?

如何在Express中修复'无法读取属性'地图'未定义'

typescript eventTarget dataset 如何修复报错?

如何修复无法找到参数[project':app']的方法实现()