1

i am trying to truncate a selected models from my application using deleteAll()

my controller:

there are a lot of models but i didn't include them for maintain as short.

<?php

namespace app\controllers;

use yii\web\Controller;
use app\models\Marks;
use app\models\ActivityHistory;
use app\models\Attendance;
use app\models\Students;
public function actionTruncate(){

    $models = array("Marks","ActivityHistory","Attendance","Students");

    foreach($models as $key=>$model){
        $model::deleteAll();
    }
   exit;
}

this getting error that

Class 'Marks' not found

when i run individual query like Marks::deleteAll(); it works. how to solve this in loop? and suggest me a good way to do this functionality

2 Answers 2

2
$models = [Marks::class, ActivityHistory::class, Attendance::class, Students::class];

foreach ($models as $model) {
     $model::deleteAll();
}
Sign up to request clarification or add additional context in comments.

Comments

2

The use statement only works for classes referenced directly. The use statement is resolved by preprocessor. It has no way to know if "Marks" string is meant to reference class or if it has some other meaning. If you want to use dynamic name of class you have to use fully qualified name of class.

The following ways of setting class names should work:

$models = array(
    //this way should always work
    "\app\models\Marks",
    "app\models\ActivityHistory",
    // ::class magic constant added in php 5.5
    Attendance::class,
    // deprecated
    Students::className(),
);

The className() method is deprecated and if you are using php 5.5 or newer you should use ::class constant instead. The method is still around for backward compatibility.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.