有两个参数的 CodeIgniter select() 方法仅返回结果集中的一列
我使用 MySQL ActiveRecord 和 CodeIgniter 来执行查询,但在使用 select()
方法时遇到了一些障碍。例如,这个 MySQL 查询在 phpMyAdmin 中完美运行:
SELECT review_id, firms_name
FROM reviews AS r
JOIN firms AS f ON f.firms_id = r.review_target_id
WHERE r.review_id =3
ORDER BY r.review_timestamp DESC
LIMIT 0 , 30
它为我提供了两列,正是我所需要的。
然而,这只给了我一列,“review_id”:
$this->db->select('review_id', 'firms_name');
$this->db->from('reviews as r');
$this->db->join('firms as f', 'f.firms_id = r.review_target_id');
$this->db->where('r.review_id', $id);
$this->db->order_by('r.review_timestamp', 'desc');
$query = $this->db->get();
如果我删除“select”子句,我会得到我需要的所有信息,但想了解我做错了什么以及如何减少我的负载数据库。
I'm using MySQL ActiveRecord with CodeIgniter to execute queries, but have run into some snags when using the select()
method. For instance, this MySQL query works perfectly within phpMyAdmin:
SELECT review_id, firms_name
FROM reviews AS r
JOIN firms AS f ON f.firms_id = r.review_target_id
WHERE r.review_id =3
ORDER BY r.review_timestamp DESC
LIMIT 0 , 30
It gives me two columns, exactly what I need.
However, this only gives me one column, "review_id":
$this->db->select('review_id', 'firms_name');
$this->db->from('reviews as r');
$this->db->join('firms as f', 'f.firms_id = r.review_target_id');
$this->db->where('r.review_id', $id);
$this->db->order_by('r.review_timestamp', 'desc');
$query = $this->db->get();
If I delete the 'select' clause, I get all the information I need, but would like to understand what I'm doing wrong and how I can reduce the load on my db.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
应该这样写(列名应该是单个字符串):
另外,请记住,您始终可以使用
$this->db->last_query();
输出最后一个查询已运行,因此您可以看到正在执行的确切 SQL 语句。should be written like this (the column names should be a single string):
Also, remember that you can always use
$this->db->last_query();
to output the last query that was run, so you can see the exact SQL statement being executed.CodeIgniter 的
select()
查询的签名如下所示:最多有 2 个参数,第二列专门用于确定是否应对第一个参数中的字符串实现转义。
在方法体的更下方,有一个条件保护子句,如果传入的
$escape
值是布尔值,则保留该值,否则保留$escape
值被覆盖。这些因素解释了为什么作为第二个参数传入的第二个列名称被忽略,而框架没有出现任何问题。
正如已经说过的,只需将多个列作为单个逗号分隔的字符串传递给
select()
即可。模型方法的完整实现:
The signature of CodeIgniter's
select()
query looks like this:There is a maximum of 2 parameters and the second column is exclusively used to determine if escaping should be implemented on the string in the first parameter.
A little bit further down in the method body, there is a conditional guard clause which preserves the passed in
$escape
value if it is a boolean value, otherwise the$escape
value is overwritten .These factors explain why the second column name passed in as the second parameter is being ignored without so much as a hiccup from the framework.
As has been already said, just pass multiple columns to
select()
as a single comma-separated string.Full implementation of the model method: