dongxian5735 2011-08-01 07:34
浏览 8
已采纳

为什么要“以编程方式像活动记录?”编写MySQL查询?

I'm working with the TinyMVC framework, and it allows one to "build MySQL queries programmatically, much like active record." The example is embedded here (relevant TinyMVC documentation):

class Members_Model extends TinyMVC_Model
{
  function get_members()
  {
    $this->db->select('foo,bar,baz'); // set selected columns
    $this->db->from('mytable');  // set from what table(s)
    $this->db->where('foo','test'); // where foo='test'
    $this->db->orwhere('foo=? and bar=?',array('test','test2')) // where foo='test' and bar='test2'
    $this->db->join('jointable','mytable','jointable.foo=mytable.foo'); // join tables on (optional) condition
    $this->db->in('mycolumn',$elements,$islist,$prefix) // IN clause: column, elements (comma-separated or array), $list=boolean is list or array, $prefix: AND|OR
    $this->db->orderby('ordercolumn'); // order by column(s)
    $this->db->groupby('groupbycolumn'); // group by column(s)
    $this->db->limit($limit,$offset); // query limit, optional offset
    $this->db->query();
    while($row = $this->db->next()) {
      $rows[] = $row;
    }
    return $rows;
  }
}

How is this different or better than the writing the SQL query outright:

SELECT foo, bar, baz
FROM mytable
WHERE...
  • 写回答

6条回答 默认 最新

  • douxieti6851 2011-08-01 07:38
    关注

    The benefit is that you can have interdependent functions in your controller that can build on your query without having to worry about the order of your SQL. You can have conditional logic to use certain active record manipulations on one query and then simply run it when it's fully populated.

    CodeIgniter's active record implementation is extremely useful. I imagine TinyMVC's is very similar.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)