开发者

Adding a timestamp property to a relation in Symfony2

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", t开发者_JAVA技巧ype="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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜