Question

The model method read() in CakePHP returns only one record, so we don't need to loop arround the result set as follws:

//In Controller
$item = $this->Item->read(null,$id);
$this->set(compact('item'));

//In View
echo $item['Item']['title'];

However, I'd like to be able to control the result through some conditions and read() method does not offer the ability to add conditions, so I have to use find() method as follows:

//In controller
$item = $this->Item->find('all',array('conditions' => array('id' => $id, 'lock' => 'yes')));
$this->set(compact('item'));

//In View
echo $item[0]['Item']['title'];

Is there any solution allows find to return only one record, i.e. I don't have to deal with $item[0] and just $item as the first example?

Was it helpful?

Solution

Never ever use read(), always use find(first):

$item = $this->Item->find('first', $options);

see http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-first

read() is concidered bad practice as it changes the model itself and usually does more harm than good - especially if you don't know or expect the exact results of this method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top