【问题标题】:Yii CActiveDataProvider data is not loading from joined tablesYii CActiveDataProvider 数据未从连接表中加载
【发布时间】:2014-04-28 12:03:30
【问题描述】:

我的代码:

$criteria = new CDbCriteria();

//  $criteria->select = array("id");

$criteria->with = array('userProfiles'=>array(
    'select'=>'firstname'
));
$criteria->together = true;

$criteria->condition = "firstname like '%$q%' "
        . "and (user_id not in (select id2 from friends where id1=$user_id) "
        . "and user_id not in (select id1 from friends where id2=$user_id))";

$dataProvider = new CActiveDataProvider("Users", array(
    'criteria' => $criteria
));

return $dataProvider;

注意事项:

1- userProfiles 关系在用户模块中定义

问题:

尽管提供了选择属性 'select'=>'firstname',但它仅从 User 表而不是从 user_profiles 表加载数据

我想要来自useruserProfile 表的数据。

【问题讨论】:

  • 不就是Users的拼写错误吗?不是只有User在你activedataprovider吗?
  • 它的工作,不是拼写问题?
  • 显示 userProfiles 关系
  • @Alex, 'userProfiles' => 数组(self::HAS_ONE, 'UserProfile', 'user_id'),

标签: php mysql yii cactivedataprovider


【解决方案1】:

关系self::HAS_ONE不能和主查询一起执行,试试join

$criteria->select = "*, user_profiles.firstname firstname"; $criteria->join = 'user_profiles ON user_profiles.user_id = users.id';

类似这样,但您应该在用户 AR 中创建名字字段来检索它。

或更改与 HAS_MANY 的关系并检查数组的第一个实体。

together: 与此关系关联的表是否应该强制与主表和其他表连接在一起。此选项仅对 HAS_MANY 和 MANY_MANY 关系有意义。

因为你不能编写查询,每个加入记录只会给你一个记录

SELECT * FROM main
INNER JOIN slave ON (slave.main_id = main.id limit 1) // will not work);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多