CakePHP - paginate and sort hasMany association

情到浓时终转凉″ 提交于 2019-12-23 21:15:53

问题


I have three tables:

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

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>

I just can't sort data by language type!

Can anyone suggest a fix for this problem?


回答1:


You can use the virtual field feature in order to sort by language type.

First, add this virtual field to your Document model:

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

Then, sort by language type in this way:

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


来源:https://stackoverflow.com/questions/34705257/cakephp-paginate-and-sort-hasmany-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!