[英]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.