1

I have a table called Settings with fields key, value and in a view I have to show 5 items from this table using CakePHP, in Controller's action I have put this:

$this->set('config', array(
        'key1' => $this->Setting->getValue('key1'),
        'key2' => $this->Setting->getValue('key2'),
        'key3' => $this->Setting->getValue('key3'),
        'key4' => $this->Setting->getValue('key4'),
        'key5' => $this->Setting->getValue('key5')

    ));

and in Setting->getValue(); I have this:

function getValue($strKey){
        $value = $this->find('first', array(
            'conditions' => array(
                'key' => $strKey
             ),
            'fields' => array(
                'Setting.value'
            )
        ));
        return $value['Setting']['value'];
    }

there's a more "CakePHP way" to do that?

Thanks.

Juliano Lima
  • 709
  • 3
  • 10
  • 17

2 Answers2

1

I would probably do it this way:

$this->find(
   'list', 
   array(
      'conditions' => array(
          'OR' => array(
                array('key' => 'key1'),
               /*etc*/
           ),
       ),
       'fields' => array('key', 'value)
    )
);

You should get an array that looks like this:

 array('key1' => 'val1', 'key2' => 'val2', /*etc*/);
Kai
  • 3,803
  • 1
  • 16
  • 33
1

Well you are retrieving values one by one which is not the right way.

Do it in a single query by making array of values:

$inArray = array('val1','val2','val3','val4','val5');

function getValue($inArray){
     $returnData = $this->find('list',array(
                       'conditions' => array('key'=>$inArray),
                       'fields' => array('key', 'value))
             );
     return $returnData;
      }

The answer given by @kai contains OR statement which is not optimised way of making such queries, for reference: MYSQL OR vs IN performance

Community
  • 1
  • 1
Anubhav
  • 1,605
  • 4
  • 18
  • 31