Yii cdbcriteria select relationship columns

It’s very difficult for me to select the usernames of all posts in the demo version of the blog given in Yii ..

the author belongs to the post class with the user ...

$criteria = new CDbCriteria; $criteria->with='author'; $criteria->select='author.username'; $dataProvider=new CActiveDataProvider('Post', array( 'criteria' => $criteria, )); var_dump($dataProvider->getData()); 

Error:

The active Message entry is trying to select an invalid column "author.username". Note: the column must exist in the table or be an expression with an alias.

+6
source share
3 answers

that with is is eager loading .. this means the relationship data will also be loaded from the database together, and when you name the relationship, there will be no actual request.

What choice does he make, he selects it from the database and maps it to the model variable ..

Now in your case, what happens is that you are trying to write a relationship column in select that will be present in select even without writing it , but since the corresponding yii variable does not exist to match this, causing an error.

So, first of all, if you need an auther username in response, you can get it by calling a relation, which will not be a database call, and you do not need to write select.

And if you want to name the username as part of the post model only , you need to declare it as a property in the model, and then specify an alias in select.

 $criteria = new CDbCriteria; $criteria->with='author'; $criteria->select='author.username as auther_username'; $dataProvider=new CActiveDataProvider('Post', array( 'criteria' => $criteria, )); var_dump($dataProvider->getData()); 

and in your Post model declare ..

 public $auther_username; 

It will no longer cause an error, and you can access your user name in both directions .. $post->auther_username and $post->auther->username

+8
source

Try the following:

 $criteria = new CDbCriteria; $criteria->with=array('author'=>array('select'=>'username')); // you can still select Post table columns here $criteria->select='post_content'; $dataProvider=new CActiveDataProvider('Post', array( 'criteria' => $criteria, )); var_dump($dataProvider->getData()); 
+1
source

Try the following:

 $criteria = new CDbCriteria; $criteria->with=array('author'=>array('select'=>'username')); $dataProvider=new CActiveDataProvider('Post', array( 'criteria' => $criteria, )); var_dump($dataProvider->getData()); 

Source: CActiveRecord.with

To configure the parameters on the fly, we must pass an array to () parameter. Array keys are relationship names and array values ​​are the corresponding query parameters.

+1
source

Source: https://habr.com/ru/post/908829/


All Articles