Codeigniter / Datamapper没有正确生成关系查询

时间:2012-12-14 18:46:12

标签: php codeigniter codeigniter-datamapper

我有一个使用Codeigniter / Datamapper的应用程序。有一个医生表,一个专业表和模型设置为具有多对多的关系。

我注意到,试图通过专业查询医生导致它只是询问所有的医生。以前有人有这个问题吗?这是我正在使用的代码:

$s = new Specialty();
$s->where('id',$id)->get(); //thought maybe get_by_id($id) was causing the issue, it wasnt...
$this->out['query'] = $s->doctor->order_by('last_name','asc')->get_sql();
$docs = $s->doctor->order_by('id')->get_iterated();

$ this-> out ['query']使用以下sql查询进行响应:

"SELECT * FROM (`doctors`) ORDER BY `doctors`.`last_name` asc"

另一个奇怪的事情是,结果不是由last_name排序,但是我假设它是如何将数组传递给json_encode函数的。

1 个答案:

答案 0 :(得分:0)

您需要向get_sql方法添加一些参数,因为您在相关对象上使用此参数。

来自docs

$object->get_sql()

This method returns the SQL for the currently built query, as if get() was called. It clears the current query immediately.

Arguments

$limit: (Optional) Sets the limit on the query.
$offset: (Optional) Sets the offset on the query.
$handle_related: (Optional) If TRUE, and this object is referenced from a parent object, the parent object will automatically to the where statement.


$u = new User();
$u->where('name', 'Bob');
echo $u->get_sql();
// outputs the raw SQL
Example with relationship
$group = new Group(1); // load Group #1

echo $group->user->get_sql();
// SELECT `users`.*
// FROM `users`

echo $group->user->get_sql(NULL, NULL, TRUE);
// SELECT `users`.*
// FROM `users`
// LEFT OUTER JOIN `groups` groups ON `users`.`group_id` = `groups.id`
// WHERE `groups`.`id` = 1

所以你需要这样做才能输出正确的查询:

$this->out['query'] = $s->doctor->order_by('last_name','asc')->get_sql(NULL, NULL, TRUE);