[英]How to implement “WHERE NOT IN” query into Codeigniter Active records?
我有一个MySQL查询,它是:
SELECT * FROM tbl_post WHERE tbl_post.post_id NOT IN
(SELECT tbl_readsave.post_id FROM tbl_readsave)
我想将其转换为Codeigniter Active记录,因此我使用了以下代码段:
$this->db->select('tbl_readsave.post_id');
$queryReadSave = $this->db->get('readsave');
$this->db->where_not_in('post_id', $queryReadSave->result_array());
$queryNewPost = $this->db->get('readsave');
if($queryNewPost->num_rows()>0)
{
return $queryNewPost->result_array();
}
else
return false;
但是,代码向我抛出错误,如下所示:-
Error Number: 1054
Unknown column 'Array' in 'where clause'
SELECT * FROM (`tbl_readsave`) WHERE `post_id` NOT IN (Array)
Filename: /var/www/html/teamF/tharjumal/models/webservice_model.php
Line Number: 28
如何将上述查询转换为Codeigniter Active Records格式?
$queryReadSave->result_array()
返回一个数组数组。 您不能在where_not_in
使用它。
您需要循环遍历并创建您(不需要)的ID的平面数组。
$this->db->select('post_id');
$queryReadSave = $this->db->get('readsave');
$postIDs = $queryReadSave->result_array();
$this->db->where_not_in('post_id', array_column($postIDs, 'post_id'));
$queryNewPost = $this->db->get('post');
array_column()
仅在PHP 5.5+中存在。 如果您使用的是较低版本,则需要执行以下操作:
$this->db->select('post_id');
$queryReadSave = $this->db->get('readsave');
$postIDs = array_map(function($a){
return $a['post_id'];
}, $queryReadSave->result_array());
$this->db->where_not_in('post_id', $postIDs);
$queryNewPost = $this->db->get('post');
PS您的第二张桌子叫post
,对吧? 您需要更新查询以使用正确的表。
更新:您的原始查询使用CodeIgniter本身不支持的子查询 。 如果您想一次尝试全部操作,则可以使用我创建的子查询库( https://github.com/NTICompass/CodeIgniter-Subqueries )。
$this->db->select('*');
$this->db->from('post');
$sub = $this->subquery->start_subquery('where_in');
$sub->select('post_id')->from('readsave');
$this->subquery->end_subquery('post_id', FALSE);
$queryNewPost = $this->db->get();
试试下面的代码:
$read_post_id = [];
$queryReadSave = $this->db->select('post_id')->get('tbl_readsave')->result_array();
if(count($queryReadSave) > 0){
foreach($queryReadSave as $row){
$read_post_id[] = $row['post_id']; // add each post id to the array
}
}
$this->db->select('*');
if(!empty($read_post_id)) $this->db->where_not_in('post_id',$read_post_id);
$post = $this->db->get('tbl_post');
print_r($post->result_array());
exit;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.