我有两个模型,Model_Post
和Model_Category
。我已经设法"找到"所有相关数据($post->$categories一样简单),但现在我需要在帖子创建/更新/删除时在帖子和多个类别之间创建关系(在posts_categories表中)。
这是Model_Post
protected static $_many_many = array(
'categories' => array(
'table_through' => 'posts_categories',
'key_through_from' => 'post_id',
'model_to' => 'Model_Category'
)
);
Model_Category
protected static $_properties = array(
'id',
'name',
'created_at',
'updated_at'
);
protected static $_many_many = array(
'posts' => array(
'table_through' => 'posts_categories',
'key_through_from' => 'id',
'key_through_to' => 'post_id',
'model_to' => 'Model_Post'
)
);
posts_categories表字段:id, name
。
我被困在这里。我应该如何构建查询?
$post->categories = Model_Category::forge()->set(array(
// I can't get any further
),
);
我还需要为关系表创建模型吗?
对于帖子和类别模型之间的多对多关系,您的数据库中应该有三个表:帖子、类别和categories_posts。
前两个不需要解释,第三个是处理两个模型之间的多/多关系。它的结构应该类似于这样:
CREATE TABLE `categories_posts`
(
`category_id` BIGINT UNSIGNED NOT NULL,
`post_id` BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (`category_id`, `post_id`)
);
$post一个Model_Post对象,$post>类别是关联类别的数组,我们就可以开始工作了。
要开始关联,我们伪造一个新的Model_Category对象并将其添加到数组中:
// forge object
$category = Model_Category::forge();
// set name
$category->name = 'Brand New Category';
// associate with Posts
$post->categories[] = $category;
/**
* we can repeat the last three steps as many times as we want
* or as many times as we need
*/
// finally, save the relation
if ($post->save(true, true)) {
echo "Everything OK";
} else {
echo "Houston, we've got a problem!";
}
请注意传递给 save() 方法的两个布尔参数。它们将分别通过关系级联和使用事务。在一次性关联模型时使用它是个好主意。
您应该阅读ORM文档,如果您会在多对多关系中找到类似示例,等等。