【问题标题】:Redbeanphp one to one relationredbeanphp 一对一关系
【发布时间】:2014-05-16 15:04:50
【问题描述】:

在我的项目中,我的数据库中有 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;
        }
    }
}

如果有任何帮助,将不胜感激

【问题讨论】:

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


【解决方案1】:

您无需更改任何内容 - 您的方式是正确的。线

$user->account = $account;

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

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

echo $user->account;

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

【讨论】:

    【解决方案2】:

    不用将帐户 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 访问帐户实例 (如果存在一对一或一对多映射的约束是)

    $account = $user->account;
    

    【讨论】:

    • 这是不正确的 - 进行您建议的更改不会为 $user->account 创建必要的外键关系。
    猜你喜欢
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    • 2011-03-30
    • 2018-10-03
    • 2013-02-12
    • 2015-08-30
    • 1970-01-01
    相关资源
    最近更新 更多