1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CakePHP2でvirtualFieldでpaginateしたいときの解決法

Posted at

virtualFieldの使い方。
基本
Modelで定義する場合

public $virtualFields =[
    'hoge' => 'COUNT(Model.huga_id)'];
//hogeにfuga.idの合計を定義する

動的に定義

$this->Model->virtualFields =['hoge' =>'COUNT(Model.huga_id)'];
$this->Model->find('all'[
    'fields' =>['hoge']
]);

またバーチャルフィールドには制限があり、関連モデルのcondition等に用いることができない。
https://book.cakephp.org/2.0/ja/models/virtual-fields.html#id6
Model1はModel2に対してhasManyの関係
動的にModel1でModel2のカラムからvirtualFieldsを作成し,paginateを利用しソートしたい時に困った
ex)Model1をModel2を持ってる数の多い順にする

$this->Model1->virtualFields = ['hoge'=>'count(Model2.model1_id)'];

$this->paginate =[
'limit' => 10,
'order' => 'Model1.hoge DESC',
'group' => ['Model1.id'],
'joins' => [[
    'table' => 'model2',
    'alias'  => 'Model2',
    'type'  => 'left',
    'conditions' => ['Model1.id'=>'Model2.model1_id']
]]
];
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?