Pradeepta
Pradeepta

Reputation: 458

cakephp find('all') get the last matched record

enter image description here

Hi all i am want perform $this->Model->find('all'); on the broadcasts table where i have to fetch only the last broadcast id of each model like 4 for model 12 and 6 for model 13.i have done this by using a simple mysql query as below.

SELECT * FROM broadcasts WHERE id IN(SELECT MAX(id) FROM broadcasts GROUP BY model_id);

But i want to know how to implement this in cakephp.

Please give your valuable feedback.

Upvotes: 1

Views: 1569

Answers (3)

Harpartap Singh Permar
Harpartap Singh Permar

Reputation: 289

Use This it will work fine :-

<?php
      $data=$this->Brodcast->find('all',
        'fields' => array('MAX(id) AS maxid', 'model_id'), 
        'group'=>'model_id'
        );
      ?>

Upvotes: 0

Daljeet Singh
Daljeet Singh

Reputation: 714

Hi You should try rewriting your query to:-

$options['fields'] = array( 'MAX(id) AS maxid', 'model_id' );
$options['group'] = array( 'model_id' );
$this->ModelName->find( 'all', $options );

Upvotes: 0

Sharma Vikram
Sharma Vikram

Reputation: 2470

Mysql query you should use mysql query for getting record The query is

SELECT max(id),model_id FROM `model` group by model_id

Output

enter image description here

Cakephp find query

<?php
  $data=$this->Brodcast->find('all',
    'fields' => array('MAX(id) AS maxid', 'model_id'), 
    'group'=>'model_id'
    );
  ?>

Upvotes: 6

Related Questions