5

I'm trying to get a video from my video database, the selection is based on a unique combination of external_id and language_id (both integers). I tried the following code, but it looks like findFirst() only picks up the first criterium

$video = Video::findFirst("language_id=" . $language->id . " and external_id=" . $external->id);

Can anybody help me how to properly use findFirst with multiple criteria?

kero
  • 10,647
  • 5
  • 41
  • 51
KBoek
  • 5,794
  • 5
  • 32
  • 49
  • The code should work. Are you sure it is failing ("looks like" doesn't sound too confident)? – kero Jun 19 '14 at 16:20
  • Found it. For some reason the external_id was set to UNIQUE in the database, cause errors on any new inserts with the same external_id, but a different language id. Thanks for you help though. – KBoek Jun 19 '14 at 17:02

2 Answers2

15

Try binding your parameters vs. concatenating them. Safer and it might identify an error area

$video = Video::findFirst(
    [
        'columns'    => '*',
        'conditions' => 'language_id = ?1 AND external_id = ?2',
        'bind'       => [
            1 => $language->id,
            2 => $external->id,
        ]
    ]
);
Nikolaos Dimopoulos
  • 11,495
  • 6
  • 39
  • 67
  • 1
    Found it. For some reason the external_id was set to UNIQUE in the database, cause errors on any new inserts with the same external_id, but a different language id. Thanks for you help though. – KBoek Jun 19 '14 at 17:02
5

Both find() and findFirst() methods accept an associative array specifying the search criteria:

$robot = Robots::findFirst(array(
    "type = 'virtual'",
    "order" => "name DESC",
    "limit" => 30
));

$robots = Robots::find(array(
    "conditions" => "type = ?1",
    "bind"       => array(1 => "virtual")
));


// What's the first robot in robots table?
$robot = Robots::findFirst();
echo "The robot name is ", $robot->name, "\n";

// What's the first mechanical robot in robots table?
$robot = Robots::findFirst("type = 'mechanical'");
echo "The first mechanical robot name is ", $robot->name, "\n";

// Get first virtual robot ordered by name
$robot = Robots::findFirst(array("type = 'virtual'", "order" => "name"));
echo "The first virtual robot name is ", $robot->name, "\n";

continue reading here: Main Doc - Finding Records

M2sh
  • 741
  • 1
  • 11
  • 23
Lukas Liesis
  • 24,652
  • 10
  • 111
  • 109