简体   繁体   中英

primary/foreign key relationship in doctrine

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM