0

我在使用 datamapper 时遇到了一点问题,我想知道是否有快速的解决方案。假设我有这种数据

组表

id   |   Name
1    |   admin
2    |   guest
3    |   editor
4    |   moderator

在我的基本控制器中,我设置了一个全局字段以仅查看非管理员组

$this->groups_ = new Group();
$this->groups_->where('id >', 1)->get();

//so I can select the users that are not admin
$users = new User();
$users->where_related('group',$id,$this->groups_)->get();

现在在我的控制器中,我想过滤组。例如,我只想选择编辑和客人(id 介于 1 和 4 之间)。所以我想过滤初始结果集......像这样

$this->groups_->where('id <',4)->get();

但它不起作用。它返回所有组 id < 4,包括管理员。得到这个的正确方法是什么?

4

2 回答 2

0

一个可能的解决方案

也许我通过克隆 datamapper 对象找到了一种可能的解决方法。我想要做的不是多次查询数据库,而是我想要一个基本结果集并优化结果。

所以在我的基本控制器中,我会做类似的事情

$this->groups_ = new Group();
$this->groups_->where('id >', 1);//without getting the results

//so I can select the users that are not admin
$users = new User();
//here i'm getting the results from the clone
$users->where_related('group',$id,$this->groups_->get_clone()->get())->get();

而且,当我让对象“打开”时,没有得到结果,我可以在我的控制器中使用它,作为我其他“查询”的基础......好吧,它们实际上是第一个查询的新条件。

//now the query return the groups between 2, as I set in the base controller
//and 4, set in the child controller
$this->groups_->where('id <',4)->get();
于 2011-11-08T15:07:00.733 回答
0

好吧,datamapper 不会查询对象或对象组。它查询数据库。因此,当您执行第二个操作时get(),您正在对数据库执行单独的查询。

您可以这样做,但这将是一个额外的查询:

$this->groups_->where('id >', 1)->where('id <', 4)->get();

或者您可以在 php 中的第一个查询后循环$this->groups_并在那里过滤集合并保存为数组。

于 2011-11-02T14:15:10.580 回答