在 Symfony2 中向关系添加时间戳属性
我正在尝试用两个实体(用户和帖子)建模一个简单的评论系统。 User 类具有常规属性,Post 类如下所示:
class Post
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* User who posted activity
*
* @var User
* @ORM\ManyToOne(targetEntity="Acme\AppBundle\Entity\User")
*/
protected $user;
/**
* @var string $text
*
* @ORM\Column(name="text", type="string", length=255)
*/
private $text;
/**
* @var datetime $timestamp
*
* @ORM\Column(name="timestamp", type="datetime")
*/
private $timestamp;
}
我需要进行一个简单的关联 - 用户可以收藏帖子。合乎逻辑的做法是将 User 类中的 ManyToMany 关联添加到 Post 中,
@ORM\ManyToMany(targetEntity="Post")
然后将创建一个以 user_id 和 post_id 作为主键的映射表。现在我的问题是我需要添加一个时间戳属性来跟踪用户何时喜欢帖子。一种可能性是创建一个新的实体“FavouritePost”,使用 ManyToOne 关联将其映射到 User 和 Post 类,并向其添加时间戳属性。
1)这是在 Symfony2 中执行此操作的正确/唯一方法吗?
2) 如果我想选择最近的 15 个帖子,并检查当前登录的用户是否喜欢这些帖子,我该如何编写查询?
感谢任何帮助,因为我对如何通过 Symfony 进行操作一无所知
I am trying to model a simple comment system with 2 entities - User and Post. The User class has the regular properties, and the Post class looks like this:
class Post
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* User who posted activity
*
* @var User
* @ORM\ManyToOne(targetEntity="Acme\AppBundle\Entity\User")
*/
protected $user;
/**
* @var string $text
*
* @ORM\Column(name="text", type="string", length=255)
*/
private $text;
/**
* @var datetime $timestamp
*
* @ORM\Column(name="timestamp", type="datetime")
*/
private $timestamp;
}
I need to make a simple association - Users can favourite posts. The logical thing to do would be to add ManyToMany association in User class to Post like so
@ORM\ManyToMany(targetEntity="Post")
Which would then create a mapping table with user_id and post_id as primary keys. Now my problem is that I need to add a timestamp property to track when the user liked a post. One possibility is to create a new Entity "FavouritePost", map it to both User and Post class using ManyToOne association, and add a timestamp property to it.
1) Is this the right/only way to do it in Symfony2?
2) If I want to select the most recent 15 posts, and check if the currently logged in user has liked the posts, how can I write a query for that?
Any help appreciated, as I am drawing a blank on how to do it via Symfony
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
1) 是的,您可以创建一个 joinure 表,以及它的 FavouritePost 实体。
2) 您应该使用 存储库 来创建所有特殊的查询:
@ORM\Entity(repositoryClass="Acme\AppBundle\Repository\FavouritePostRepository")
然后很容易进行 Doctrine 查询,就像您会做更多一样。
1) Yes you may create a jointure table, and so its FavouritePost entity.
2) You should use a Repository to create all special queries :
@ORM\Entity(repositoryClass="Acme\AppBundle\Repository\FavouritePostRepository")
Then it's easy Doctrine queries, like you will make much more.