Find a record where id is not the primary key in fuelphp

316 views Asked by At

Is there any way to find a record using ORM in fuelphp if the primary key of the table is not id column?

For example, listing_id is my primary key. And I couldn't get the desired result with:

$listing_id = Input::get('listing_id');
$entry = Model_ExampleData::find($listing_id);
2

There are 2 answers

0
Tpojka On BEST ANSWER

protected static $_primary_key

By default this is set to array('id'), if you use another column name or multiple primary keys you need to set this property.

class Model_Article extends Orm\Model
{
    protected static $_primary_key = array('aid');
}

The primary key must be a real primary key: unique and unchanging. Don't use it for other purposes (like a foreign key in a one-one relation) as well, that won't work as the PK can't be changed. The Orm won't check this, and while it might seem to work at first glance: you'll get into trouble. It is not required for the PK to be auto_increment (though preferred) and you can specify the PK yourself, but only the first time. Once it's set, it's set.

Docs .

0
Miky On

You have magical method prefixes for this purpose: find_by_

By adding this prefix, you can tell FuelPHP to find record(s) using arbitrary fields in your model without modifying model configurations, and multiple condition is possible with splitting field names by _and_ between them.

Model_ExampleData::find_by_FIELD($value)
Model_ExampleData::find_by_FIELD1_and_FIELD2($value1, $value2)
Model_ExampleData::find_all_by_FIELD($value)
Model_ExampleData::find_all_by_FIELD1_and_FIELD2($value1, $value2)
Model_ExampleData::count_by_FIELD($value1)