php-如何在学说中定义n-m关系?
作者:互联网
如果有一个表“ Article”和一个表“ Tags”.文章可以具有多个标签,标签可以挂在多个文章上.
类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"
解决方法:
要建立多对多关系,您必须将关系放在关联表中,而不是联接表中,如下所示:(简化)
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-> Tags之类的操作.
在Doctrine Documentation中有更多信息.
标签:relationship,doctrine,schema,php 来源: https://codeday.me/bug/20191210/2099487.html