【问题标题】:Codeigniter: Combining activeRecord with manual queries?Codeigniter:将 activeRecord 与手动查询相结合?
【发布时间】:2011-02-28 10:35:46
【问题描述】:

我对 Codeigniter 中的 activerecord 与手动查询有所了解。当 ActiveRecord 完全是关于标准查询并且开发时间非常短时,它非常棒。

但是,当需要增加查询的复杂性时,ActiveRecord 的使用会变得相当复杂。子查询或复杂的连接至少让我很头疼。

由于当前的 "$this->db->query" -call 立即执行 set 查询,它不能与正常的 activeRecord 调用结合。

那么,我可以做些什么来结合这两种方法呢?

我想要完成的示例:

$this->db->select('title, content, date');
$this->db->from('mytable');
$this->db->manual('UNION'); // My own idea of db-call that appends UNION to the query
$this->db->select('title, content, date');
$this->db->from('mytable2');
$query = $this->db->get();

谢谢!

【问题讨论】:

  • 向我们展示一个复杂查询的例子,也许我们可以考虑如何使用 ActiveRecord 来完成它。 AFAIK 如果这是你的意思,你不能结合 $this->db->query() + $this->db->get()。
  • 您好,这其实是我想了一段时间的事情,所以我现在恐怕没有具体的例子。正如你所说,我知道 $this->db->query() + $this->db->get() 不能组合:)
  • 我和波格丹在一起,一个示例查询会很好。
  • 大家好,用我想做的例子更新了我的原始帖子。这可能是用更高级的东西扩展 activeRecord 功能的好方法,而不必从头开始编写整个查询......

标签: php mysql database activerecord codeigniter


【解决方案1】:

也许这个链接会有所帮助:active record subqueries

更新---

还有另一个关于Union with Codeigniter Active Record 的讨论。我同意那里的答案。

但是对于一些子查询,我们可以将活动记录与手动查询结合起来。示例:

// #1 SubQueries no.1 -------------------------------------------

$this->db->select('title, content, date');
$this->db->from('mytable');
$query = $this->db->get();
$subQuery1 = $this->db->_compile_select();

$this->db->_reset_select();

// #2 SubQueries no.2 -------------------------------------------

$this->db->select('title, content, date');
$this->db->from('mytable2');
$query = $this->db->get();
$subQuery2 = $this->db->_compile_select();

$this->db->_reset_select();

// #3 Union with Simple Manual Queries --------------------------

$this->db->query("select * from ($subQuery1 UNION $subQuery2) as unionTable");

// #3 (alternative) Union with another Active Record ------------

$this->db->from("($subQuery1 UNION $subQuery2)");
$this->db->get();

nb:抱歉,我还没有测试过这个脚本,希望它有效且有用..

【讨论】:

  • 嗨,Bakazero。感谢您的链接。非常感激。请查看我的原帖。用一个我想做的例子来更新它。
  • 嗨!非常喜欢你的更新。虽然没有我想要的那么干净。点赞! :)
  • 这不起作用(或不再起作用)。 _compile_select 和 _reset_select 是受保护的方法。
猜你喜欢
  • 2015-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2015-11-11
  • 2018-02-22
  • 1970-01-01
相关资源
最近更新 更多