如果有一个表“文章”和一个表“标签”。文章可以有多个标签,标签可以挂在多个文章上。
类BaseArticle看起来像这样:
abstract class BaseArticle extends Doctrine_Record {
public function setTableDefinition() {
$this->setTableName('article');
$this->hasColumn('article_id', 'integer', 8, array(
'type' => 'integer',
'length' => 8,
'fixed' => false,
'unsigned' => false,
'primary' => true,
'autoincrement' => true,
));
$this->hasColumn('title', 'string', null, array(
'type' => 'string',
'fixed' => false,
'unsigned' => false,
'primary' => false,
'notnull' => false,
'autoincrement' => false,
));
$this->hasColumn('text', 'string', null, array(
'type' => 'string',
'fixed' => false,
'unsigned' => false,
'primary' => false,
'notnull' => false,
'autoincrement' => false,
$this->hasColumn('url', 'string', 255, array(
'type' => 'string',
'length' => 255,
'fixed' => false,
'unsigned' => false,
'primary' => false,
'notnull' => false,
'autoincrement' => false,
));
}
public function setUp() {
parent::setUp();
$this->hasMany('Tag as Tags', array( 'local' => 'article_id',
'foreign'=>'tag_id',
'refClass'=>'Articletag')
);
}
}
像这样的BaseTag类:
abstract class BaseTag extends Doctrine_Record {
public function setTableDefinition() {
$this->setTableName('tag');
$this->hasColumn('tag_id', 'integer', 4, array(
'type' => 'integer',
'length' => 4,
'fixed' => false,
'unsigned' => false,
'primary' => true,
'autoincrement' => true,
));
$this->hasColumn('name', 'string', null, array(
'type' => 'string',
'fixed' => false,
'unsigned' => false,
'primary' => false,
'notnull' => false,
'autoincrement' => false,
));
}
public function setUp() {
parent::setUp();
$this->hasMany('Article as Articles', array( 'local' => 'tag_id',
'foreign'=>'article_id',
'refClass'=>'Articletag')
);
}
}
关系类是这样的:
abstract class BaseArticletag extends Doctrine_Record
{
public function setTableDefinition()
{
$this->setTableName('articletag');
$this->hasColumn('article_id', 'integer', 8, array(
'type' => 'integer',
'length' => 8,
'fixed' => false,
'unsigned' => false,
'primary' => true,
'autoincrement' => false,
));
$this->hasColumn('tag_id', 'integer', 4, array(
'type' => 'integer',
'length' => 4,
'fixed' => false,
'unsigned' => false,
'primary' => true,
'autoincrement' => false,
));
}
public function setUp()
{
parent::setUp();
}
}
当我尝试从文章中获取属性时,使用以下内容一切顺利:
$article = Doctrine_Query::create()->from('Article a')
->where('id = ?' , 1)
->fetchOne();
echo $article->title; //gives me the title
但是当我尝试这个时:
foreach($article->Tags as $tag) {
echo($tag->name)
}
我收到错误:
Unknown record property / related component "Tags" on "Article"
答案 0 :(得分:3)
要设置多对多关系,您必须将关系放在关联表中,而不是连接表中,如下所示:(简化)
Article
...
Relations:
Tags:
class: Tag
local: article_id
foreign: tag_id
refClass: ArticleTag
Tag
...
Relations:
Articles:
class: Article
local: tag_id
foreign: article_id
refClass: ArticleTag
ArticleTag:
(no relations)
然后您就可以执行诸如$ article->标签之类的操作。 Doctrine Documentation。
中的更多信息答案 1 :(得分:0)
事实证明,Doctrine或我对关系的定义并没有错。问题的原因是项目中已经有一个名为“Tag”的类。在重命名该类之后,该学说关系工作得很好: - )