0

In my project have 2 entites in my db namely User and Account. One User has one account.User table has account_id field as foreign key to reference Account entity. I am generating automaticly a new account for user. Everything gets created as I expect.But how can I reference an account for a parcticular user. Here is my registration script

public function register ($data = null)
{
    if ($data != null) {
        try {
            $user = R::dispense('user');
            $user->name = $data['name'];
            $user->lastname = $data['last-name'];
            $user->username = $data['username'];
            $user->password = $data['password'];
            $user->email = $data['email'];
            $user->city = $data['city'];
            $user->country = $data['country'];
            //create account for user
            $account = R::dispense('account');
            $account->account_no = $this->genAccountNumber();
            $account->money_sum = 0;
            $user->account = $account;
            $id = R::store($user);
            return $id;
        } catch (Exception $e) {
            echo $e->getMessage;
        }
    }
}

Would be grateful for any help

Andriy Haydash
  • 357
  • 1
  • 14
  • 35

2 Answers2

0

You don't need to change anything - your way is correct. The line

$user->account = $account;

is the right way to do it - assuming you are running in fluid mode, your schema will be updated automatically to create the foreign key relationship for you this way.

To access the account, you just need to use $user->account.

echo $user->account;

will show you all the properties of the account bean.

charliefortune
  • 3,072
  • 5
  • 28
  • 48
-1

Instead of giving account bean as foreign reference to user bean, just add account_id field as foreign key to user table.

public function register ($data = null){
if ($data != null) {
    try {
        $user = R::dispense('user');
        $user->name = $data['name'];
        $user->lastname = $data['last-name'];
        $user->username = $data['username'];
        $user->password = $data['password'];
        $user->email = $data['email'];
        $user->city = $data['city'];
        $user->country = $data['country'];
        //create account for user
        $account = R::dispense('account');
        $account->account_no = $this->genAccountNumber();
        $account->money_sum = 0;
        $account_id = R::store($account);
        $user->account_id = $account_id;   // this is the line you have to change
        $id = R::store($user);
        return $id;
    } catch (Exception $e) {
        echo $e->getMessage;
    }
}}

And when loading a bean you can directly access account instance from user bean (constraint being if there is a one-to-one or one-to-many maaping)

$account = $user->account;
ratan
  • 1
  • This is incorrect - making the change you suggest won't create the necessary foreign key relationship for $user->account to work. – charliefortune Jan 15 '16 at 09:14