Redbeanphp一对一的关系

时间:2014-05-16 15:04:50

标签: php orm one-to-one relation redbean

在我的项目中,我的数据库中有2个用户,即用户和帐户。一个用户有一个帐户。用户表将account_id字段作为引用帐户实体的外键。 我正在为用户自动生成一个新帐户。一切都按照我的期望创建。但我怎样才能为一个特定用户引用一个帐户。这是我的注册脚本

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;
        }
    }
}

非常感谢任何帮助

2 个答案:

答案 0 :(得分:0)

你不需要改变任何东西 - 你的方式是正确的。这条线

$user->account = $account;

是正确的方法 - 假设您在流畅的模式下运行,您的架构将自动更新,以此方式为您创建外键关系。

要访问该帐户,您只需使用$ user->帐户。

echo $user->account;

将显示帐户bean的所有属性。

答案 1 :(得分:-1)

不要将帐户bean作为外部对用户bean的引用,只需将account_id字段作为外键添加到用户表。

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;
    }
}}

加载bean时,您可以直接从用户bean访问帐户实例 (约束是指如果存在一对一或一对多的mapping)

$account = $user->account;