dongshanxiao7328 2011-10-27 16:10
浏览 22
已采纳

主义/外键关系在学说中

On my mysql db, I have two tables: "User" And "UserProfile". The table "UserProfile" has a foreign key column named 'user_id' which links to "User" table's "id" column. Now, when I am generating all entity classes from my db tables using doctrine, the created "UserProfile" class contains a property named 'user'(which is of "User" type) and doesn't contain any property named 'user_id'. Is it ok?

Now, if I want to find a user's profile, given the user_id, I needed to write something like this:

$user_profile_repo = $this->em->getRepository("UserProfile");

$user_profile = $user_profile_repo->findOneBy(array("user_id"=>$id));

But as the generated entity class doesn't include the "user_id" property, the above code won't work. Now I need to know how can I do the tweak to make the above code work please? Thanks.

  • 写回答

1条回答 默认 最新

  • duannaoben8011 2011-10-27 16:46
    关注

    the actual names of the tables/columns in the database are not really important. you can set them in the comments.

    it should be something like this:

    /**
     * models\User
     * @Table(name="User")
     * @Entity
     */
    class User
    {
        /**
         * @Column(name="id", type="integer", precision=0, scale=0, nullable=false, unique=false)
         * @Id
         * @GeneratedValue(strategy="IDENTITY")
         */
        private $id;
    
        /**
         * @Column(name="name", type="string", length=50, precision=0, scale=0, nullable=false, unique=false)
         */
        private $name;
    
        /**
         * @OneToOne(targetEntity="models\UserProfile", mappedBy="user")
         */
        private $profile;
    }
    
    
    /**
     * models\UserProfile
     * @Table(name="UserProfile")
     * @Entity
     */
    class UserProfile
    {
        /**
         * @OneToOne(targetEntity="models\User", inversedBy("profile"))
         * @JoinColumn(name="user_id", referencedColumnName="id")
         */
        private $user;
    }
    

    in this case a user has the column id, and the userprofile has user_id

    once generated, you should get in the User the method getProfile() and in the UserProfile you should get getUser()

    it is similar to 5.7 oneToOne bidirectional: http://www.doctrine-project.org/docs/orm/2.0/en/reference/association-mapping.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面