Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 model rules, how to use another table whilst using exist?

Tags:

php

yii2

I want to check if the categoryid given is an existing category. I've tried several values as the target attribute, but I can't get it working so far.

When I execute the query as is, it returns the correct value for what I am trying to add.

public function rules()
{
    return [
        [['categoryid'], 'integer'],    
        ['categoryid', 'exist', 'targetAttribute' => FaqCategory::findOne(['id=:id', ['id'=>'categoryid']])['id']],
        [['question', 'answer'], 'required'],
        [['answer'], 'string'],
        [['question'], 'string', 'max' => 255]
    ];
}
  • Update

I stumbled upon targetClass. However this time around I receive Class 'FaqCategory' not found. Class is to be found under the same namespace.

 ['categoryid', 'exist', 'targetClass' => 'FaqCategory'] 
like image 429
Wijnand Avatar asked Jan 06 '15 15:01

Wijnand


2 Answers

You have to use class name with namespace, it should be something like :

['categoryid', 'exist', 'targetClass' => '\app\models\FaqCategory'] 

Or

['categoryid', 'exist', 'targetClass' => FaqCategory::className()] 

http://www.yiiframework.com/doc-2.0/guide-tutorial-core-validators.html#exist

like image 159
soju Avatar answered Nov 15 '22 21:11

soju


Got the answer thanks to soju. Just needed to add the targetAttribute to compare the categoryid to the id of the category.

['categoryid', 'exist', 'targetClass' => '\app\models\FaqCategory', 'targetAttribute' => 'id'],
like image 45
Wijnand Avatar answered Nov 15 '22 19:11

Wijnand