A way to find one in CakePHP

12,015

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.

Share:
12,015

Related videos on Youtube

SaidbakR
Author by

SaidbakR

Listen to your heart and smile This is a short success story. My LinkedIn Profile! | My GitHub Repos. Just a Developer! Free Secure your Windows Computer against Viruses with Avast Anti Virus ##My favorite Answer:## Search for value in multidimensional array and get parent array in PHP If you find some useful answers or questions, please +1 vote! (x2 + y2 − 1)3 − x2y3 = 0 Chimply: Generate loading image indicators, buttons and badges. ###Main Tags### php javascript jquery cakephp sql mysql array ▒▒sємsєм▒▒ ▒▒ ▒▒ ▒▒▒▒▒▒▒▒▒▒ ▒▒▒▒▒▒▒▒▒ ▒▒▒▒▒▒▒▒▒▒ ▒▒▒▒▒▒▒▒▒ القرآن الكريم Important Notice: Chimply.com is not my own website, but it is a website, I just like it!

Updated on June 04, 2022

Comments

  • SaidbakR
    SaidbakR almost 2 years

    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?

  • mark
    mark about 11 years
    its not. at least not in the current versions of it. what source are you referring to? it has also been removed from the (official) tutorials. See: github.com/cakephp/cakephp/blob/master/lib/Cake/Console/…
  • usii
    usii about 11 years
    nice question and logic to deal with out [0]. :)
  • SaidbakR
    SaidbakR about 11 years
    @mark The upgrade is very good idea. However, I stuck at some projects I started them with CakePHP 1.2.x and I don't need more time delay in-order to manage migration.