PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, March 6, 2022

[FIXED] Yii cdbcriteria select a relation's columns

 March 06, 2022     php, yii     No comments   

Issue

I am having very difficult time to select usernames of all posts in the blog demo given in Yii..

author is relation of post class with user...

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

Error:

Active record "Post" is trying to select an invalid column "author.username". Note, the column must exist in the table or be an expression with alias.


Solution

what with does is eager loading..that means the relation's data will also loaded from database alongwith, and when when u'll call the relation, there won't be a actual query..

What select does is it selects it from database and maps it to model variable..

Now in your case what is happening is you're trying to write some relation's column in select, which will be there in select even without writing it, but as there is no corresponding variable to map this value yii is throwing an error..

So first thing if you need to username of auther in response, you can get it by relation calling, which won't be a database call, and u dont need to write a select..

And if u want to call the username as a part of the post model only u have got to declare it as a property in model, and then specify 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;

Now it won't throw error, and you can access the username by both ways..$post->auther_username, and $post->auther->username



Answered By - Rajat Singhal
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing