【问题标题】:CakePHP - paginate and sort hasMany associationCakePHP - 分页和排序 hasMany 关联
【发布时间】:2016-01-10 22:04:59
【问题描述】:

我有三张桌子:

Book -> belongTo -> Document ,Document -> hasOne -> Book, Document -> hasMany -> Language , Language - > belongTo -> 文档

Document.php

public $hasOne = array(
    'Book' => array(
        'className' => 'Book',
        'foreignKey' => 'document_id',
        'dependent'=>true,
    )

public $hasMany = array(
    'Language' => array(
        'className' => 'Language',
        'foreignKey' => 'document_id'
    )

Book.php

public $belongsTo = array(
    'Document' => array(
        'className' => 'Document',
        'foreignKey' => 'document_id'
    )
);

Language.php

public $belongsTo = array(
    'Document' => array(
        'className' => 'Document',
        'foreignKey' => 'document_id'
    )
);

BooksController.php

    $this->Book->bindModel(array(
        'hasOne' => array(
            'Language' => array(
                'foreignKey' => false,
                'conditions' => array('Document.id = Language.document_id')
    ));

    $this->Prg->commonProcess();
    $this->Paginator->settings = [
        'conditions' => $this->Book->parseCriteria($this->Prg->parsedParams()),
        'contain' => array('Document','Language')
    ];
    $this->set('books', $this->Paginator->paginate());

index.php

            <th><?php echo $this->Paginator->sort('Document.Language.type',__('language')); ?></th>

我只是无法按语言类型对数据进行排序!

谁能建议解决这个问题?

【问题讨论】:

    标签: sorting cakephp paginator


    【解决方案1】:

    您可以使用虚拟字段功能按语言类型排序。

    首先,将此虚拟字段添加到您的 Document 模型中:

    public $virtualFields = ['Min_LangType' => 'SELECT MIN(type) FROM languages as Language WHERE Language.document_id = Document.id'];
    

    然后,以这种方式按语言类型排序:

    $this->Paginator->sort('Document.Min_LangType',__('language'));
    

    【讨论】:

    • 非常感谢!您的虚拟字段是 Min_LangType 因此您应该在 index.php 中说 Document.Min_LangType。我不敢相信答案这么简单!
    猜你喜欢
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    相关资源
    最近更新 更多