dongxian5735 2011-08-01 07:34 采纳率: 0%
浏览 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条)

报告相同问题?