Yii cdbcriteria 选择关系的列 [英] Yii cdbcriteria select a relation's columns

查看:25
本文介绍了Yii cdbcriteria 选择关系的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难选择 Yii 中给出的博客演示中所有帖子的用户名..

author 是 post class 与 user 的关系...

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

错误:

活动记录Post"正在尝试选择无效的列author.username".注意,该列必须存在于表中或者是带有别名的表达式.

解决方案

with 所做的是eager loading..这意味着关系的数据还将从数据库中加载,以及何时调用关系,不会有实际查询..

select 的作用是从数据库中选择它并将其映射到模型变量..

现在在你的情况下发生的事情是你试图在select中写一些关系的列,即使没有写它也会在select中存在,但是因为没有相应的变量来映射这个值yii是抛出错误..

所以首先如果你需要 auther 的用户名作为响应,你可以通过关系调用得到它,这不会是一个数据库调用,你不需要写一个选择..

如果你想把用户名作为post模型的一部分来调用,只有你必须在模型中将它声明为一个属性,然后在select中指定别名..

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

<块引用>

并在您的 Post 模型中声明..

public $auther_username;

现在不会报错了,你可以通过两种方式访问​​用户名..$post->auther_username, and $post->auther->username

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.

解决方案

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

这篇关于Yii cdbcriteria 选择关系的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆