gpt4 book ai didi

php - DataMapper ORM 简单的 OneToMany 关系

转载 作者:行者123 更新时间:2023-11-29 13:31:54 25 4
gpt4 key购买 nike

这是我的关系模型的开始;

ERD

我不使用 DataMapper 的冗余方式来为所有内容建立一个关系表,但我似乎还不能这样做;

代码

<?php
$brand = new Brand(1);

var_dump($brand->themes->get());

品牌

    var $has_many = array(
'themes' => array(
'class' => 'theme',
'join_table' => 'themes'
)
);
}

主题

<?php

class Theme extends DataMapper {

var $has_one = array(
'brand' => array(
'join_table' => 'brands',
)
);

}

这会导致brands.id字段失败;

SELECT `themes`.*
FROM (`themes`)
LEFT OUTER JOIN `brands` brands ON `themes`.`id` = `brands`.`theme_id`
WHERE `brands`.`brand_id` = 1 # <<< Wrong :(

我阅读了文档,但似乎我读得太牵强了。我不想使用关系表,除非它是真正的多对多关系。

最佳答案

编辑您的模型:

品牌

var $has_many = array(
'theme'
)

主题

var $has_one = array(
'brand'
)

现在您可以轻松获取 Controller 中的信息。如果您想列出某个品牌的主题,请使用:

$_brand = new Brand;
$brand = $_obrand->get_by_id(1);
foreach($brand->themes AS $theme) {
echo $theme->name;
}

注意:上面的示例需要在配置中自动加载关系,请参阅 manual :

$config['auto_populate_has_many'] = TRUE;
$config['auto_populate_has_one'] = TRUE;

关于php - DataMapper ORM 简单的 OneToMany 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19331920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com