【发布时间】:2011-02-07 12:21:03
【问题描述】:
如果有一个表格“文章”和一个表格“标签”。文章可以有多个标签,标签可以挂在多篇文章上。
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"
【问题讨论】:
-
在阅读文档并查看大量示例后,我仍然找不到问题所在。会不会是在 Doctrine 1.2.1 中破坏了 n-m 关系?
-
多对多关系没有中断,我每天都在使用它们。使用我在答案中提供的代码应该可以工作......哦,顺便说一下,如果在 hasColumn() 调用中用简单的“id”替换“article_id”和“tag_id”是否有效?
标签: php schema doctrine relationship