MeekroDB Quick Start Docs ORM Docs FAQ
Download GitHub

Related Tables and Associations

It's quite common for objects to be related. For example, an Account object might have multiple Tickets that are stored in another table.

class Account extends MeekroORM {
  static $_associations = [
    'Tickets' => ['type' => 'has_many', 'foreign_key' => 'account_id', 'class_name' => 'Ticket'],
  ];
}

class Ticket extends MeekroORM {
  // the tickets table has an account_id column for which account owns the ticket
  static $_associations = [
    'Account' => ['type' => 'belongs_to', 'foreign_key' => 'account_id'],
  ];
}

// the has_many Tickets assoc lets us pull up the tickets from the account
$Account = Account::Load(1);
foreach ($Account->Tickets as $Ticket) {
  // do something with each ticket
}

// if you start with a ticket, you can also grab the corresponding account
$Ticket = Ticket::Load(12345);
echo "The ticket email is {$Ticket->Account->email}\n";

Association Types

has_many -- The other table (not ours) has the id, and there can be multiple matching rows. In the example above, the Account class can have multiple Tickets associated with it, and the tickets table has an account_id column identifying the account ownership.

has_one -- Just like has_many, except there can only be one matching record.

belongs_to -- There can only be one matching record, and we have the id in our table.

Other Fields

foreign_key -- The column that has to correspond to the primary key. For has_one or has_many, the foreign_key is a column in the other table that has to match our primary key. For belongs_to, it is a column in our table that has to match the other table's primary key.

class_name -- The class name of the other table; it must be a class that inherits from MeekroORM. If not specified, we assume it's the same as the association name.

Loading and Accessing Associated Objects

Both belongs_to and has_one types are guaranteed to return one object (or none). When you first access an association, the corresponding MeekroORM object will be loaded. When you access the same one again, the same object will be accessed from memory. You can see this happening in the example above.

On the other hand, has_many associations will always be an array because they can return one or more objects. You can access them like an array, or use the scope functions to narrow the list before accessing it.