skip to Main Content

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 appcontrollers;

use yiiwebController;
use appmodelsMarks;
use appmodelsActivityHistory;
use appmodelsAttendance;
use appmodelsStudents;
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


  1. 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
        "appmodelsMarks",
        "appmodelsActivityHistory",
        // ::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.

    Login or Signup to reply.
  2. $models = [Marks::class, ActivityHistory::class, Attendance::class, Students::class];
    
    foreach ($models as $model) {
         $model::deleteAll();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search