V
V
Vladimir Klintsov2020-10-31 19:18:39
Yii
Vladimir Klintsov, 2020-10-31 19:18:39

Yii2 relations NULL Foreign key How to do CREATE/UPDATE correctly?

People, such trouble:
There is a groups table
... ... And there is a files table ...
'file_id' => $this->integer(),

'id' => $this->primaryKey()->notNull()->unique(),
'filename' => $this->string(),

...
$this->addForeignKey(
            'file-id',
            'groups',
            'file_id',
            'files',
            'id',
            'CASCADE'
        );

Gii generated:
class Groups extends \yii\db\ActiveRecord
{
...
[['file_id'], 'default', 'value' => null],
[['file_id'], 'integer'],
[['file_id'], 'exist', 'skipOnError' => true, 'targetClass' => Files::className(), 'targetAttribute' => ['file_id' => 'id']],
...
public function getFile()
{
    return $this->hasOne(Files::className(), ['id' => 'file_id']);
}
...
class Files extends \yii\db\ActiveRecord
{
...
public function getGroups()
{
    return $this->hasMany(Groups::className(), ['file_id' => 'id']);
}
...
public function actionMyaction($id)
{
...
$model = $this->findModel($id);  
...
return $this->render('Myaction', [
    'model' => $model,
]);

Now, in the Myaction form, if there is a non-NULL file_id value in the Groups table and a corresponding value in the Files id table, I can get the filename value:

<?= $form->field($model->file, 'filename')->textInput(); ?>


The trouble starts if there is no corresponding value in the Files table
Call to a member function isAttributeRequired() on null

I assume that there should be New Files() somewhere, but where?
Please Help!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question