J
J
Justique2017-05-05 21:36:37
Yii
Justique, 2017-05-05 21:36:37

Why doesn't Yii2 ActiveRecord Model delete?

I don't understand why Call to a member function delete() error
776a1a5413d5418bb16d1ec797466dff.png
7b6858f7877544c3b78ad04645ba165e.png
Here is the model

<?php
namespace common\models;

use Yii;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;

/**
 * UserToSection model
 *
 * @property integer $id
 * @property integer $user_id
 * @property integer $section_id
 */
class UserToSection extends ActiveRecord
{
  


    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id]);
    }
  
}

Accessing the Model
$section = UserToSection::findAll([
        'user_id' => \Yii::$app->user->getId()
      ]);
      print_R($section);
      $section->delete();

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
Justique, 2017-05-05
@Justique

I asked myself, I answer myself

$section = UserToSection::deleteAll([
        'user_id' => \Yii::$app->user->getId()
      ]);

M
Maxim Timofeev, 2017-05-07
@webinar

findAll returns an array of objects, so
either like this:

$section = UserToSection::findAll(['user_id' => \Yii::$app->user->getId()]);
foreach($section as $one){
$one->delete();
}

either like this:
UserToSection::deleteAll([
        'user_id' => \Yii::$app->user->getId()
      ]);

But keep in mind that the second method does not use events, which means that beforeDelete and afterDelete are bypassed. But 1 is more resource-intensive naturally.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question