Validation Role

I create this validation function

 public function workerUniq($attributes,$params)//


        isset($_POST['Activity']['activity_code']) ? $activity_code=$_POST['Activity']['activity_code']&$flag=TRUE:'';

        $timetable_code = $_POST['Activity']['timetable_code'];

        $workers_code = $_POST['Activity']['workerToActivity'];

        $criteria = new CDbCriteria();

        $criteria->with = array('workers');

        $criteria->together = true;


        $criteria->condition = 'timetable_code=:timetable_code AND worker_code=:worker_code';


                  foreach ($workers_code as $v1){

                        $criteria->params = array(':timetable_code'=>$timetable_code,':worker_code'=>'$v1->worker_code');





                                $this->addError('workerToActivity','worker alredy besy');


                        }  else {

                            $this->addError('workerToActivity','worker alredy besy');






the DB is:

three tables: "activity","worker" and "worker to activity"

and i want to make sure that a worker is register only to one activiy at any "timecode"

the relations between worker to activity meny-meny

and it retren SQL error, what am i doing wrong?

it is ok to put the citeria parm in the foreach?

What is the SQL error?

For me prefixing column names in relation conditions helps preventing a lot of trouble. Could be it. But give us the SQL error, then we can help you out maybe.


SQLSTATE[23000]: Integrity constraint violation: 1052 Column ‘worker_code’ in where clause is ambiguous. The SQL statement executed was: SELECT COUNT(DISTINCT t.activity_code) FROM tbl_activity t LEFT OUTER JOIN tbl_worker_to_activity workers_workers ON (t.activity_code=workers_workers.activity_code) LEFT OUTER JOIN tbl_worker workers ON (workers.worker_code=workers_workers.worker_code) WHERE (timetable_code=:timetable_code AND worker_code=:worker_code)

Because the column ‘worker_code’ is in more tables, SQL don’t know which one you mean with:

 $criteria->condition = 'timetable_code=:timetable_code AND worker_code=:worker_code';

So you have to use the table alias. Something like:

 $criteria->condition = 'timetable_code=:timetable_code AND workers.worker_code=:worker_code';


Besides that, I wonder if you could do it with the default unique validator somehow: to check on the "worker to activity" class.

    public function rules(){

        array('worker_code', 'unique', 'className'=> 'WorkerToActivity'),


I’ll try that thenks!

so it’s not return error but also not prevent doble worker situation

and the unique rule not working either :(

You can have more unique rules if you want. And also you can use a condition in the unique rule.