Reputation: 6154
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.
Upvotes: 1
Views: 2949
Reputation: 5290
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
Upvotes: 1