pdo 获取对象?
有没有更好的方法返回数据库结果的对象?
我知道“return $statement->fetchall(PDO::FETCH_CLASS, 'modelClassName');
”,但它只适用于 fetchall 函数?
class modelArea extends Model {
public $areaID;
public $postcode;
public static function find($condition, $parameters) {
$query = "SELECT * FROM area WHERE " . $condition;
$statement = self::getDb()->prepare($query);
if (!$statement->execute($parameters))
return false;
$query = $statement->fetch(PDO::FETCH_ASSOC);
$a = new modelArea();
$a->areaID = $query['areaID'];
$a->postcode = $query['postcode'];
return $a;
}
}
Is there a better way to return object of db result?
I am a aware "return $statement->fetchall(PDO::FETCH_CLASS, 'modelClassName');
" but it only work on fetchall function?
class modelArea extends Model {
public $areaID;
public $postcode;
public static function find($condition, $parameters) {
$query = "SELECT * FROM area WHERE " . $condition;
$statement = self::getDb()->prepare($query);
if (!$statement->execute($parameters))
return false;
$query = $statement->fetch(PDO::FETCH_ASSOC);
$a = new modelArea();
$a->areaID = $query['areaID'];
$a->postcode = $query['postcode'];
return $a;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
PDOStatement::fetchObject
方法的作用你想要的。您可以像这样使用它:
这将导致
$a
成为modelArea
类的对象,相当于您给出的代码。The
PDOStatement::fetchObject
method does what you want.You can use it like:
This will result in
$a
being an object of classmodelArea
, equivalent to the code you give.您可以创建 modelArea 类(或单独的工厂类)的静态方法并调用:
甚至可以创建一个返回 modelArea 对象数组的方法
You could create a static method of the
modelArea
class (or a separate factory class) and call:or even have one that returns an array of
modelArea
objects