php - CodeIgniter:如果 Active Record 找不到任何数据,则返回 FALSE

标签 php codeigniter activerecord

使用 CodeIgniter,我在所有从数据库收集数据的模型中找到以下代码:

// .. taken from function get_user_data($user_id)
// Select data
$user_data = $this->db->from('users')->where('id', $user_id)->get()->row();

// Check if we got any matches
if(isset($user_data->id)) {

  // Indeed we did, return the data found
  return $user_data

} else {

   // Nope, no data found
   return FALSE;

}

有趣的部分是我检查查询是否实际返回了任何数据。我对每个查询都这样做,加起来相当多的重复代码

有什么方法可以覆盖 CodeIgniter 函数,使它们在未找到数据时返回 FALSE? 我可能遗漏了一些东西,因为我不明白为什么 CodeIgniter 还没有处理这个问题。

最佳答案

内置快捷方式的方式并不多。即使是 manual建议检查您的结果:

If you run queries that might not produce a result, you are encouraged to test the result first:

$query = $this->db->query("YOUR QUERY");
if ($query->num_rows() > 0)
{
   // found results
}

你总是可以使用类扩展:

class MY_Model extends CI_Model {

    protected function _get_row($result)
    {
        return $result->num_rows() ? $result->row() : FALSE;
    }

}

模型中的用法:

function get_user_data($user_id)
{
    $user_data = $this->db->from('users')->where('id', $user_id)->get();
    return $this->_get_row($user_data);
}

您只需要extends MY_Model 为您想要访问该功能的模型。

另一种选择是返回 $this->db->get() 的结果,并在您的 Controller 中进行检查(您可能无论如何都必须这样做)。

关于php - CodeIgniter:如果 Active Record 找不到任何数据,则返回 FALSE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11478924/

相关文章:

php - Doctrine - 来自的子查询

PHP动态图像

php - 使用 PHP 从数据库中检索后汇总值

php - Active Record 不唯一表问题

ruby-on-rails - Rails 3 忽略 Postgres 唯一约束异常

ruby-on-rails - 在rails中继承active_record

php - 将输出流式传输到文件和浏览器

PHP安装配置: error: Cannot find php_pdo_driver. h

PHP Mysqli multi_query 和触发器的分隔符

mysql - 获取所有当前连接到 yii2 ActiveQuery 中的查询