【问题标题】:Codeigniter - Use the id from a query result in a model to query in a different function in the same modelCodeigniter - 使用模型中查询结果中的 id 在同一模型中的不同函数中进行查询
【发布时间】:2013-04-02 14:28:46
【问题描述】:

我正在使用 codeigniter 对我的网站进行编码,但遇到了障碍。我知道如何在常规的非“MVC”中做到这一点,而不是 OOP PHP,但我在 Codeigniter 中苦苦挣扎。

我有 blog_model.php,它具有从我的数据库中检索日期时间的功能,将其分解为一个数组,以便我可以在模型之外使用它并将其提供给我有单独的日历图标的 CSS。每个日历图标都按视图中的月份编号 (<div class='calendar-icon-$stats['date']) 加载。此函数还从单个帖子中提取 cmets 的数量并将其输出到数组中,以便我可以在视图中显示它。

public function get_stats($id) {
  $this->db->select('id,datetime')->from('blog_posts')->where('id',$id);
  $dquery = $this->db->get();
  $dquery = $dquery->row_array();
  $date = date('Y-m-d', strtotime($dquery['datetime']));
  $stats = explode("-", $date); // This makes $stats[0] the year, $stats[1] the month and $stats[2] the day.
  $stats['time'] = date('H:i', strtotime($dquery['datetime']));
  $stats['comcount'] = $this->db->get_where('blog_comments', array('blogid' => $id));
  $stats['comcount'] = $stats['comcount']->num_rows();
  return $stats;
}

还有一个函数可以检索最近的三个条目:

public function get_blog_last() {
  $query = $this->db->order_by('id desc')->get('blog_posts',3);
  return $query->result_array();
}

此代码然后被加载到我的控制器中并发送到要显示的视图:

$data['blog'] = $this->blog_model->get_blog_last();
$data['stats'] = $this->blog_model->get_stats($data['blog']);
$this->load->view('index',$data);

我面临的问题是如何让 get_stats() 函数为我在索引页面上的每个条目运行,其中显示了最后三个条目。到目前为止,我只能为其中一个运行它,因此我首页上的所有三个条目都具有相同的日期、相同的时间和相同数量的 cmets。我认为将代码放入模型中可以避免重复自己,因为我必须为存档页面(我显示该月的所有帖子)和我只显示该条目及其 cmets 的主条目页面加载它。

所以,这里的终极问题是:

  • 如何为给定页面上的每个条目运行 get_stats?

我在确定传递给我的 get_stats() 函数的正确值时也遇到了一些问题。

任何指导将不胜感激。提前谢谢你。

【问题讨论】:

    标签: php codeigniter function model


    【解决方案1】:

    如果我的理解正确,您需要为您在get_blog_last 中收到的三个条目中的每一个致电get_stats。如果是这种情况,只需将get_blog_last 更改为:

    public function get_blog_last() {
      $query = $this->db->order_by('id desc')->get('blog_posts',3);
      $entries = $query->result_array();         // get the latest entries array
      foreach ($entries as $index => $entry) {   // loop through those entries
        $stats = $this->get_stats($entry['id']); // call this model's `get_stats` method
        $entries[$index]['stats'] = $stats;      // add a `stats` key to the entry array
      }
      return $entries;
    }
    

    【讨论】:

    • 废话。就是这么简单!我觉得很笨。非常感谢!
    【解决方案2】:

    你为什么不放

    $this->blog_model->get_stats($data['blog']);
    

    内循环? (我宁愿使用普通循环)

    示例:

    $stat_list = array();
    for($i=0;$i<count($data['blog']);$i++){
        $stat_list[] = $this->blog_model->get_stats($data['blog'][$i]);
    }
    $data['stats'] = $stat_list;
    

    在您看来,您应该尝试同样的方法来打印每个$stat_list

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-05
      • 1970-01-01
      • 2015-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多