There are four tables
Articles:(id, body)
Questions (id, body)
Votes (id, user_id, votable_id, vote_type)
comments(id, user_id, body, commentable_id, comment_type)
vote stores users’ like records for Articles and Questions; use vote_type to distinguish whether the stored records are likes for articles or questions
id | user_id | votable_id | vote_type | illustrate |
---|---|---|---|---|
1 | 2 | 1 | article | This record indicates that user 2 liked article 1 |
1 | 2 | 1 | question | This record indicates that user 2 liked question 1 |
comments stores user response records to Articles and Questions; use commentable_type to distinguish whether the stored records are responses to articles or questions
id | user_id | commentable_id | comment_type | illustrate |
---|---|---|---|---|
1 | 2 | 1 | article | This record represents user 2’s reply to article 1 |
1 | 2 | 1 | question | This record represents user 2’s reply to question 1 |
End of background;
So how to declare the mapping relationship between them;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="articles")
*/
class Article
{
//...
/**
*
* @ORM\OneToMany(targetEntity="Vote", mappedBy="votable")
*/
$votes;
}
class Vote
{
//...
/**
*
* @ORM\ManyToOne(targetEntity="Article|Question?", inversedBy="votes")
*/
$votes;
}
为情所困2017-07-03 11:44:27
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="articles")
*/
class Article
{
// ...
}
/**
* @ORM\Entity
* @ORM\Table(name="articles")
*/
class ArticleVote extends Article
{
/**
*
* @OneToMany(targetEntity="VoteArticle", mappedBy="votable_id")
*/
private $id;
}
/**
* @ORM\Entity
* @ORM\Table(name="articles")
*/
class ArticleComment extends Article
{
/**
*
* @OneToMany(targetEntity="CommentArticle", mappedBy="commentable_id")
*/
private $id;
}
/**
* @ORM\Entity
* @ORM\Table(name="votes")
*/
class Vote
{
// ...
}
/**
* @ORM\Entity
* @ORM\Table(name="votes")
*/
class VoteArticle
{
/**
*
* @ORM\ManyToOne(targetEntity="ArticleVote", inversedBy="id")
*/
private $votable_id;
}
/**
* @ORM\Entity
* @ORM\Table(name="comments")
*/
class Comment
{
// ...
}
/**
* @ORM\Entity
* @ORM\Table(name="comments")
*/
class CommentArticle
{
/**
*
* @ORM\ManyToOne(targetEntity="ArticleComment", inversedBy="id")
*/
private $commentable_id;
}
Others are similar. In addition, add Criteria when querying, see https://www.boxuk.com/insight...
为情所困2017-07-03 11:44:27
@boxsnake This will create a new question
>php bin/console doctrine:schema:update --force
[Doctrine\DBAL\Schema\SchemaException]
The table with name 'symfony.votes' already exists.
doctrine:schema:update [--complete] [--dump-sql] [-f|--force] [--em [EM]] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--] <command>