0

I'm not following, how exactly I define relations in RedBean, not on the fly.

I have a user which can have a parent user that is considered an employer. On the opposite side, a user can have employees which are also users.

How would I go about defining this?

I'd like the interface to be something of this sort:

$user = R::load('user', $id);
var_dump($user->hasEmployees); // show all employees
var_dump($user->ownEmployer); // show my employer

But it looks like, I have to define them every time like this:

$user->hasEmployees = R::findAll('user', 'employer_id = ?', array($user->id));
$user->ownEmployer  = R::load('user', $user->employer_id);

Which kind of defeats the purpose of having a dynamic system. Since there's no real model (or not a very extensive one), I'm assuming you create the relations one time and use them, and RedBean knows to do so next time on?

Or do I have to define that relationship whenever I'm accessing the model? (could I use the dispense() method in the model in that case?)

If so, how does that work exactly?

What am I missing?

Thanks!

casraf
  • 21,085
  • 9
  • 56
  • 91

1 Answers1

1

You should talk a look at the relations section on redbeanphp.com. Relations are created by strict naming conventions. In your case it would work like this:

// Dispense the beans
list($employer, $employee1, $employee2) = R::dispense('employee', 3);

// Create relations
$employer->ownEmployeeList = array($employee1, $employee2);

// Demonstrate relations
var_dump($employer->ownEmployeeList); // returns $employee1 and $employee2
var_dump($employee1->employee); // returns $employer
kekub
  • 872
  • 6
  • 11
  • Would I have to 'create relations' on every usage? Or could I assume $employer->ownEmployeeList would bring me the populated list if I access it elsewhere and it has proper data in the database? – casraf Mar 30 '14 at 11:58
  • Once your tables are populated $employer->ownEmployeeList returns an array of employees. You do not need to recreate the relations. – kekub Mar 30 '14 at 12:28