Kohana, Formo and many-to-many relations (“habtm”)

Posted on September 18, 2009


Just got the solution for how to handle many-to-many relations in Formo. Thank you, Ben!

Three tables, groups (id, name), users (id, name) and the pivot table groups_users(group_id, user_id).

class User_Model extends ORM {
protected $has_and_belongs_to_many = array('groups');
class Group_Model extends ORM {
protected $has_and_belongs_to_many = array('users');

And here’s how to in the controller handle display of an user form, complete with checkbuttons for toggling connections to groups:

public function user($id = false) {
$user = new User_Model($id);
$form = Formo::factory()
->habtm('user', 'group')
if ($form->validate()) $form->save();
echo $form;

This gives the following form. The magic lies in the habtm plugin (has to be active either by Formo config or by Formo::factory()->plugin(‘habtm’). Not one single sql line, not one line of deadly tedious form populating and deriving…


Ok, not pretty, but that’s another story.

Soo proud. Just struck me what “habtm” stands for.
Na na, won’t tell ya! 🙂

Tagged: ,
Posted in: Database, Kohana PHP, PHP