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

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

报告相同问题?

悬赏问题

  • ¥20 simulink单相桥式整流电路
  • ¥35 问问51单片机流水灯的代码该怎么写
  • ¥15 关于#百度#的问题:感觉已经将字体段落、字体、页边距、纸张大小、文档网络调成与论文模板一致,为什么黄色部分字体左右的间距还是不一样啊,求私信发文件接收看一下
  • ¥15 stata webuse报错
  • ¥15 TypeError: Cannot read properties of undefined (reading 'status')
  • ¥15 如何利用AI去除图片中的竹架子
  • ¥15 python 写个基金爬取的代码,自动卖出功能
  • ¥15 Linux系统启动不起来
  • ¥15 为什么运行仿真数码管不亮(语言-c语言)
  • ¥15 陈仁良《直升机飞行动力学》小扰动线化方程如何推导