gpt4 book ai didi

php - 使用 Active Record 构建查询的优缺点

转载 作者:行者123 更新时间:2023-12-02 07:08:33 25 4
gpt4 key购买 nike

我想在我的 PHP 应用程序后端运行这个查询。理论上,sheet 是一个数据库,用于跟踪我们拥有的所有工作表。 Purchases 是一个数据库,用于跟踪哪些用户可以访问哪些工作表。我要运行的查询给出了用户的 ID,我可以获得他们应该有权访问的所有工作表。查询形式:

select distinct s.wsid, s.name from sheets s, purchases p where 
s.wsid = p.wsid AND p.uid = *value*;

其中 value 是应用程序输入的内容

在我看来,有两种方法可以让它在后端运行。

选项 1)

public function getPurchasedSheets($uid){
if( is_numeric($uid) ){ //check against injections
$query = "select distinct s.wsid, s.name from sheets s, purchases p
where s.wsid = p.wsid AND p.uid = ".$uid.";" ;
return $this->db->query($query);
} else {
return NULL; //or false not quite sure how typing works in PHP
}
}

选项 2)

public function getPurchasedSheets($uid){
if( is_numeric($uid) ){
$this->db->select('wsid, name');
$this->db->distinct();
$this->db->from('purchases');
//not sure which order the join works in...
$this->db->join('sheets', 'sheets.wsid = purchases.wsid');
$this->db->where('uid ='.$uid);
return $this->db->get();
} else {
return NULL;
}
}

所有 CodeIgniter Active Record 命令的来源:

codeigniter.com/user_guide/database/active_record.html

以这种或另一种方式做事是否存在某种性能或安全差异?第二种方式对我来说似乎更令人困惑......这有点复杂,因为我不确定如何在这种编码风格中进行引用消歧,因为购买和工作表都有一个 uid 字段,但它们意味着不同的东西(除了一开始就不太熟悉 SQL 连接命令。)。 purchases中的uid(user id)表示用户购买了该sheet,而sheets中的Uid表示哪个用户拥有该sheet。

TL,DR:基本上,我想问的是,我是否应该花时间研究如何以选项 2 的方式做事?

最佳答案

主要的好处是:

  • 数据库引擎的抽象,库可以在其中处理特定于数据库的 SQL 语法差异。相关的,如果你曾经/想要更改您正在使用的数据库。理论上,第二种形式应该仍然有效。
  • “事件记录”语法自动为您转义参数。
  • 可读性,虽然这是一个品味问题。

顺便说一句,如果您在 PHP 5 环境中,该库支持方法链:

if( is_numeric($uid) ){ 
return $this->db->select('wsid, name')
->distinct()
->from('purchases')
->join('sheets', 'sheets.wsid = purchases.wsid')
->where('uid ='.$uid)
->get();
// nb. didn't check your join() syntax, either :)
}

可能偏离主题:CodeIgniter 的 Active Record 与其说是 Active Record 的实现,不如说是一个查询生成器。如果你想知道。当被视为查询构建器时,它更有意义;) FWIW,我确实喜欢 CodeIgniter。我开玩笑是出于感情。

关于php - 使用 Active Record 构建查询的优缺点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8234546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com