douyou4819 2015-04-27 13:37
浏览 42
已采纳

Yii模型关系加入

  1. table Books
  2. table Authors
  3. table Authors_Category

In Books model have relation:

    public function relations()
    {
        return array(
            'authors' => array(self::BELONGS_TO, 'Authors', array('author_id'=>'id')),
    }

In Authors:

    public function relations()
    {
        return array(
            'authors_category' => array(self::BELONGS_TO, 'Authors_Category', array('author_cat'=>'id')),
    }

In Books DataGridView I can access Authors_Category fields

$data->authors->authors_category->category_name

But problem is in sorting Authors_Category colums

In Books model I have sorting rule:

    return new CActiveDataProvider(
        new FraudAlerts(),
        array(
            'criteria'=>$criteria,
            'sort'=>array(
                'attributes'=>array(
                    'category_name'=>array(
                        'asc'=>'Authors_Category.category_name',
                        'desc'=>'Authors_Category.category_name DESC',
                    ),
                )
            )
        )
    );

When I try sort by Authors_Category fiels I get error, that col category_name not exist.

What is wrong in my relations in Books model ?

  • 写回答

1条回答 默认 最新

  • doukuo9116 2015-04-27 14:21
    关注

    As Yatin Mistry pointed out, you have to eager load authors_category for this to work.

    Yii allows you to load nested relations using with so this can be accomplished as follows:

    $criteria->with = array(
        'authors.authors_category' => array('select' => array('category_name', 'id'))
    );
    

    The select limits the fields loaded via the query for improved performance. If you wish to load all the fields from Authors_Category just remove it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi