php - Doctrine - Add foreign key pointing to 2 target entities -
i have 3 entities; blog, project , comment. block , projects both have comments. want foreign key ref_id in comment point either blog or project using ref_type value. here entities
class blog { ... protected $id; ... protected $title; ... } class project { ... private $id; ... private $title; } class comment { ... protected $id; /** * @orm\column(type="string") */ protected $ref_type; /** * @orm\manytoone(targetentity="**project,blog**", inversedby="comments") * @orm\joincolumn(name="ref_id", referencedcolumnname="id") */ protected $ref_id; }
i new in doctrine might simple can find solution. google came across mapped superclasses not sure how relevant issue.
yes, solution subclassing blog
, project
.
prepare db
at first place, can make subclass inherent table. let super class named "commentable".
create table commentable( int id_commentable not null primary key auto_increment, title varchar(200) not null, c_type vachar(100) not null);
and then, every commentable has custom fields:
/* blog table */ create table blog(id_commentable int not null primary key, description text); /* project table */ create table project(id_commentable int not null primary key, location text);
note 3 tables above have same primary key name. mandatory
the comments table has relationship commentable table
create table comments(id_comment int not null primary key auto_increment, comment text, commentable_id int not null);
create superclass , children
according tables time start build entities.
commentable superclass
/** * @entity * @inheritancetype("joined") * @discriminatorcolumn(name="c_type", type="string") */ abstract class commentable { /** * @id * @column(type="integer", nullable=false, name="id_commentable") * @generatedvalue(strategy="auto") */ protected $id; /** * @column(type="string") */ protected $title; /** * @onetomany(targetentity="comment", mappedby="commentable") **/ protected $comments; function getcomments(){ return $this->comments; }
blog
/** * @entity * @table(name="blog") */ class blog extends commentable{ /** * @column(type="string") */ protected $title;
project
/** * @entity * @table(name="project") */ class project extends commentable{ /** * @column(type="string") */ protected $location;
comments
take in count comments point commentable
entity , not children.
/** * @entity * @table(name="comments") */ class comment{ /** * @manytoone(targetentity="commentable", inversedby="comments") * @joincolumn(name="comment_id", referencedcolumnname="id_comment") **/ protected $commentable; /** * @column(type="string") */ protected $comment;
usage
for example, if want project comments, do:
// knowing id 3 project $project = em->find('models\project', 3); $comments = $project->getcomments();
or if prefer comments not matter type:
$commentable = em->find('models\commentable', 3); $comments = $commentable->getcomments();
both examples above return same list of comments;
Comments
Post a Comment