5

Currently i have table with posts, each posts has an id.

For a moment, only one posts exists, with id id = 92.

if i execute following code, i will get not false, but post with id=92:

$post = NewsPost::findFirst(['id' => 1]);
var_dump($post->id); // gives 92 

Seems to be very strange logic.. What method could be used to retrieve post by id, and that will return false/throw exception if there is no such entity?

Nikolaos Dimopoulos
  • 11,495
  • 6
  • 39
  • 67
avasin
  • 9,186
  • 18
  • 80
  • 127

4 Answers4

7

Try this:

$post = NewsPost::findFirst("id = 1");

or

$post = NewsPost::find(
    array(
        "conditions" => "id = ?0",
        "bind"       => array(0 => 1)
    )
);
Nikolaos Dimopoulos
  • 11,495
  • 6
  • 39
  • 67
  • Btw, if i define NewsPost::findFirst("id = 1"), will id value be escaped properly by framework? – avasin Dec 18 '12 at 02:31
  • 1
    @true Yes because the Model gets translated to PHQL which always gets escaped. However I personally prefer the second option with the bound parameters. It might be an overkill since both do the same but from a visual perspective I know that I bind my parameters thus correctly sanitize and escape them. – Nikolaos Dimopoulos Dec 18 '12 at 02:34
  • Thank you very much for your answer, agree with you, second way seems more clear :) – avasin Dec 18 '12 at 02:40
5

I use:

$instance = Model::findFirst($id);

Where $id is a primary key.

starsinmypockets
  • 2,264
  • 4
  • 34
  • 45
  • 1
    I've already checked the correct answer a long time ago, but your answer is correct (and best one). I've used to use it too. – avasin Jun 06 '14 at 14:22
2

Use

NewsPost::findFirst(['id = 1']);

or

NewsPost::findFirst(1)
小灰灰
  • 21
  • 1
1

You should use:

NewsPost::findByid(1);

Where 'id' can be replaced by any of your model's properties. For example:

NewsPost::findByDescription('Description');
NewsPost::findByyourprop(yourpropval);

You can then count() the return value count($result) to determine if you received any records.

Note: I have also found the string searches to be case in-sensitive.

Jesse Q
  • 1,451
  • 2
  • 13
  • 18