2012-03-23 25 views
0

我有3个mySQL表:user,section和user_section(加入表)。将使用ISNULL的SQL查询转换为Codemapiter的Datamapper ORM

下面的SQL:

SELECT id, description, 
NOT ISNULL(
    (SELECT user_id 
    FROM user_section 
    WHERE user_section.section_id = section.id 
    AND user_id=5)) AS user_in_section 
FROM section 
WHERE site_id = 3 

很好地产生以下结果:

id description user_in_section 
3 section1  1 
8 section2  0 
9 section3  1 

我有一个表格,我认为编辑的用户和他们所属的部分。我写的复选框出像这样($ user_sections包含上述数据):

<div class="checkboxes"> 
    <?php foreach ($users_sections as $row) { ?> 
    <label class="checkbox"><input <?= ($row->checked>0?'checked':'') ?> type="checkbox" name="section[]" value="<?= $row->id ?>" /> <?= $row->description ?></label></br> 
    <?php } ?> 
</div> 

我的问题是:

有没有更好的方式来编写SQL查询?或者,我有什么好/唯一的方法来获取我想要的数据?

我想使用Datamapper ORM来编写查询。我到目前为止...

$section 
->select('sections.id, description') 
->select_func('NOT ISNULL', array('(SELECT id FROM sections_site_users where sections_site_users.site_section_id=sections.id and sections_site_users.site_user_id='.$user_id.')'), 'checked') 
->where('site_id', $site_id) 
->get(); 

NOT之前ISNULL是用单引号转义,防止查询是正确的SQL。我怎样才能在Datamapper中正确写入?

任何改进建议非常感谢。提前致谢。

编辑:

我已经找到一个可行的解决方案 - 这是我的DataMapper代码:

$sections = new Section(); 
$sections 
    ->where('site_id', $site_id) 
    ->get(); 

foreach ($sections as $s) 
{ 
    $s2 = new Section(); 
    $s2 
     ->where('id', $s->id) 
     ->where_related('user', 'id', $user_id) 
     ->get(); 

    $s->checked = ($s2->exists() ? 1 : 0); 
} 

产生相同的数据在我的答案上的SQL。但它确实使用了更多的数据库查询(我希望能够在一个数据库查询中进行查询)。

任何人都可以证实我已经做了最好的事情吗?

谢谢!

回答

0

是的!简单地说:

$user = new User(); 
$sections = $user->section->where('id', $site_id)->get_iterated(); 
foreach($sections as $section) 
{ 
    // $section->id 
    // $section->description 
} 

但是你必须正确设置你的关系!

即:

类用户: 公共$的has_many =阵列(“部分);

上一节: public $ has_many = array('user');

加入表应该是:users_sections

用户表:用户 段表:段

编辑: 你想有一个给定网站的特定用户的部分。你在网站和用户之间有一种关系。所以你会先结束加载用户,然后得到他的部分:

$user = new User($user_id); 
if ($user->result_count()) 
{ 
    $sections = $user->section->where_related_site('id', $site_id)->get_iterated(); 
} 

这应该没问题。对不起,我一开始并不明白。 模型的简短说明将有帮助:)

+0

感谢的Spir,我有我的关系,建立正常,但我没用过get_iterated还没有 - 所以我给一个尝试。你有什么机会可以帮我完成如何编写Datamapper代码来实现和我的问题顶部一样的SQL?我对细节还不清楚。谢谢。 – sculptnz 2012-03-26 22:13:53

+0

你试过我的代码: $ user = new User(); $ sections = $ user-> section-> where('id',$ site_id) - > get(); get_iterated比实现“IteratorAggregate”的经典get更快。当你遍历一组元素时,你应该使用它(参见doc:http://datamapper.wanwizard.eu/pages/getalt.html#get_iterated) – Spir 2012-03-28 11:39:19

+0

对不起,如果我没有解释得这么好......但你没有明白我想要什么。如果你看看我的问题顶部的SQL和它产生的结果,你会看到我得到一个网站的部分列表,然后对于每个部分,我得到1或0是否一个特定的用户在该部分。 无论如何,我有一个解决方案,所以我会关闭问题。 – sculptnz 2012-03-30 00:31:39