Skip to content

Instantly share code, notes, and snippets.

@dhrrgn
Created December 5, 2010 06:33
Show Gist options
  • Save dhrrgn/728870 to your computer and use it in GitHub Desktop.
Save dhrrgn/728870 to your computer and use it in GitHub Desktop.
Example of the new ActiveRecord package
<?php
namespace Fuel\Application\Model;
use ActiveRecord;
class Group extends ActiveRecord\Model {
protected $has_many = array('users');
}
<?php
namespace Fuel\Application\Model;
use ActiveRecord;
class User extends ActiveRecord\Model {
protected $belongs_to = array('group');
}
<?php
namespace Fuel\Application;
// Not required, just here for nicer syntax
use Fuel\Application\Model\User;
use Fuel\Application\Model\Group;
class Controller_Welcome extends Controller\Base {
public function action_index()
{
// Here I use the 'include' option, which includes the given association by default.
// Using this allows us to use eager loading to include all the data with 1 query.
// If you left this out and the query there were 10 rows returned, it would actually
// run 11 queries, because it would re-query every time you accesses the assoc.
// Find all the users named 'Dan' and display their ID's and what group they are in
$users = User::find_by_name('Dan', array('include' => 'group'));
foreach ($users as $user)
{
echo 'ID: '.$user->id.' - Group: '.$user->group->name.'<br />';
}
// Same thing as above, just lists all the users in a group
$group = Group::find(2, array('include' => 'users'));
foreach($group->users as $user)
{
echo $user->name.'<br />';
}
// Output the query count. This will be 2 in this scenario, if we removed
// the includes it would be N + 2, where N is the number of records returned
// for each one.
echo DB::$query_count;
}
}
@philsturgeon
Copy link

Could it be a string if there is only one association?

@dhrrgn
Copy link
Author

dhrrgn commented Dec 5, 2010

Yup.

@bencorlett
Copy link

can you add aliases for associations?

protected $has_many = array('menu_items' => 'items');

The reason is that the items model is in a subfolder under menu as it's a property of menu, and that way the tables are called:

menus
menu_items

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment