Friday, 15 July 2011

php - Condition for related table ORM Kohana -



php - Condition for related table ORM Kohana -

for illustration have 3 tables:

songs(id, song_name) song_category(id, song_id, category_id) categories(id, name)

i want songs have categories id higher 5. want using orm, not simple sql query. possible 1 query this:

$songs = orm::factory("songs")->where("category.id > 5")

no, cannot single kohana orm call.

the best way have found this, makes modification sql query orm generate:

// basic "song" model $songs = orm::factory("songs"); // info how connected // "category" model using `through` model $song_relations = $results->has_many(); $category_relation = $song_relations['categories']; $through = $category_relation['through']; // bring together on `through` model's target foreign key (far_key) , `target` model's primary key $join_col1 = $through.'.'.$category_relation['foreign_key']; $join_col2 = $songs->object_name().'.'.$songs->primary_key(); $songs->join($through)->on($join_col1, '=', $join_col2); // now, filter on $songs->where($through.'.'.$category_relation['far_key'], '>', 5); $arr = $results->find_all()->as_array();

you save code hardcoding values in join method call, way leverages orm relation definitions have.

this assumes song model has next code in it:

protected $_has_many = [ 'categories' => [ 'model' => 'category', 'through' => 'song_category', 'foreign_key' => 'song_id', 'far_key' => 'category_id', ] ];

php orm kohana

No comments:

Post a Comment