I have two tables set up in a database, a "Posts" table and an "Images" table. Rows in the Images table are related the Posts table with an ID so at any time there can be a single Post, but multiple rows from the Image table assigned to it. I don't want to run a join as it results in duplicate content from the Posts table when it adds the Posts to each row in Images
I'd like to be able to iterate through this content in the following manner:
foreach(posts as post)
{
foreach(post['image'] as image)
{
// something here
}
}
In Django, this can be set up in my model through the following:
class Posts
# something here
def get_images(self):
return self.images_set.select_related('post')
Is it possible to have a similar set up in a Codeigniter model using their Active Record? The only way I've been able to it was to query the Posts table, loop through results and query the Images table while inside the loop. Then set everything up as a new array and send it to the controller. But that doesn't seem efficient at all. Here's an example:
public function get_posts()
{
// Grab all posts
$query = $this->db->get('posts_table');
$results = $query->result_array();
// Arrays for storage
$photoArray = array();
$postsArray = array();
$postsResultArray = array();
$postsResultArray[] = $results;
// Query photos in DB
foreach($photoResultArray[0] as $row)
{
$query = $this->db->get_where('uploads', array('tableName' => 'posts_table', 'recordNum' => $row['num'], 'fieldname' => 'images'));
$results = $query->result_array();
foreach($results as $row)
{
$photoArray[] = $row;
}
}
// Associate each post with photo if available
foreach($postsResultArray[0] as $post)
{
foreach($photoArray as $row)
{
if($row['recordNum'] == $post['num'])
{
$post['image'] = $row['urlPath'];
}
}
$postsArray[] = $post;
}
return $postArray;
}
Try this
public function get_posts()
{
// Grab all posts
$query = $this->db->get('images');
$results = $query->result_array();
// Arrays for storage
$photoArray = array();
$postsArray = array();
$photoResultArray[] = $results;
// Query photos in DB
foreach($photoResultArray as $row)
{
$photoArray[$row->id] = $row->image;
}
$query2 = $this->db->get('posts');
$results2 = $query2->result_array();
$postsResultArray[] = $results2;
// Associate each post with photo if available
foreach($postsResultArray[0] as $post)
{
$postsArray[] = $photoArray[$post->image_id];
}
return $postArray;
}
Related
I want to pass multiple id in where condition how to do it?
A query fetches org_id from database.
now I want to pass that in my where condition, so how to do it?
I tried foreach loop:
Below is my code:
$devices = $this->activation_m->get_activated_devices();
$org_id = array(); // create org_id array
foreach ($devices as $row)
{
$org_id[]= $row['org_id']; // assign ids into array
//$companys =$this->data['devices'] = $this->activation_m->get_company($org_id); // don't call again and again
}
//Now $org_id is array
$companys =$this->data['devices'] = $this->activation_m->get_company($org_id);
echo $this->db->last_query();
Model Code
public function get_activated_devices()
{
$this->db->select('*');
$this->db->join('sitekey','sitekey.site_key = activation.site_key');
$this->db->from('activation');
$query =$this->db->get();
$result = $query->result_array();
return $result;
}
public function get_company($org_id)
{
$this->db->select('*');
$this->db->join('sitekey','sitekey.org_id = company.id');
$this->db->join('activation','sitekey.site_key = activation.site_key');
$this->db->where('company.id IN',(implode(',',$org_id))); // see the change here
$this->db->from('company');
$query =$this->db->get();
$result = $query->result_array();
return $result;
}
now currently my query passes only one org_id , I want to pass all the org_id I get from my first query.
You can use where_in from active-records codeigniter
as
$devices = $this->activation_m->get_activated_devices();
$org_id = array();
foreach ($devices as $row)
{
$org_id[] = $row['org_id'];
}
$companys =$this->data['devices'] = $this->activation_m->get_company($org_id);
if( $companys->num_rows() > 0 )
{
echo "<pre>";
print_r( $companys->result());
echo "</pre>";
}
And for Model
public function get_company($org_ids = array())
{
$this->db->select('*');
$this->db->join('sitekey','sitekey.org_id = company.id');
$this->db->join('activation','sitekey.site_key = activation.site_key');
$this->db->where_in('company.id', $org_ids ); //this is condition
$this->db->from('company');
return $this->db->get();
}
You can use codeigniter's $this->db->or_where() for the purpose. Just traverse the array of organization id's and apply or_where conditions.
$this->db->select('*');
$this->db->join('sitekey','sitekey.org_id = company.id');
$this->db->join('activation','sitekey.site_key = activation.site_key');
foreach($org_id as $org)
{ // where $org is the instance of one object of active record
$this->db->or_where('company.id',$org);
}
$this->db->from('company');
$query =$this->db->get();
$result = $query->result_array();
return $result;
Another way to do this is to make a custom query by traversing the array like this and appending where clauses in string.
I have built up a script to first query table 'linkags' in database for id's where 'id' is equal to 'userId' and 'type' is equal to 'type'.
I then use the result to query table 'linktagRevisions' to fetch the latest revision for the returned array of id's pertaining to that user.
I then output the list of 'linktagRevisions' in to a json output.
My issue has been that I have been unable to unserialize 'content'. So in building my array to output in json I have coded:
$data = array('linktag' => unserialize($result[$linkI]['content']));
Which successfully returns an unserialzed result, but it limits to one row even with the foreach loop in place. How can I use the loop to fetch all rows?
Here is my full code:
public function testAction()
{
//Return list of tags for the defined user and make default type 10
$u = 2;
$t = 10;
$resultid = array();
//Connect to database
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select()
->from(array('lt' => 'Linktags'),
array('id'))
->where('userId = ?', $u)
->where('type = ?', $t);
$stmt = $select->query();
$resultid = $stmt->fetchAll();
//print_r($resultid);
//Get latest revision from database and loop through $id's
$id = $resultid;
//print_r($id);
//setup array and loop
$result = array();
foreach($id as $lId_all) {
foreach($lId_all as $lId) {
//Connect to database
$db = Zend_Db_Table::getDefaultAdapter();
//Perform Query
$select = $db->select('')
->from(array('lr' => 'LinktagRevisions'),
array('content'))
->where('linktagId = ?', $lId)
->order('updated DESC')
->limit(1);
$stmt = $select->query();
$result[$lId] = $stmt->fetch();
}
}
$linkId = $resultid;
foreach ($linkId as $linkI_all) {
foreach ($linkI_all as $linkI) {
//print_r($linkI);
$data = array('linktag' => unserialize($result[$linkI]['content']));
}
print_r($data);
$this->_helper->json($data, true);
}
}
Try to add link index like this:
$data = array();
foreach ($linkId as $linkI_all) {
foreach ($linkI_all as $linkI) {
$data['linktag'.$linkI] = unserialize($result[$linkI]['content']);
}
}
$this->_helper->json($data, true);
the following algorithm add users to a company array. I want to add a total of user for any given company. Howd I go about doing that
public function all_company_information($id = null){
$arrCompany = array();
$arrCompany['company']= array();
$arrData = array();
$this->autoRender = false;
$this->loadModel("User");
$users = $this->User->find('all');
foreach($users as $k => $user){
if(!in_array($user['User']['company_id'], $arrCompany['company'])){
$arrCompany['company'][$user['User']['company_id']][] = $user;
}else{
$arrCompany['company'][$user['User']['company_id']][] = $user;
}
}
}
Do a find on the Company model, then you can get a count of users easily.
$results = $this->Company->find('all');
foreach($results as $k => $company) {
$results[$k]['Company']['user_count'] = count($company['User']);
}
Something along those lines. The returned results will be an array of Company records and each Company record will have a list of associated user records in the User key.
How to access values from codeigniter's ci_sessions table's "user_data" column in CodeIgniter.
I have added user_name, user_role in session. I have to display all active users name and their roles.
This is how I would do it:
$query = $this->db->select('user_data')->get('ci_sessions');
$user = array(); /* array to store the user data we fetch */
foreach ($query->result() as $row)
{
$udata = unserialize($row->user_data);
/* put data in array using username as key */
$user[$udata['user_name']] = $udata['user_role'];
}
You can then iterate over $user, print its contents, etc.
I got solution:
view file name is "admin_active_users.php" and
$data is dispalying whole information.
calling controller function:active_users()
function active_users() {
$this->load->model('admin_model');
$query =$this->admin_model->get_active_users();
$num_row=$query->num_rows();
$result=$query->result();
$str="<br/><b>$num_row</b> Users are active at this time<br/>";
$str.="<table border=1 cellpadding=2><tr><td>User Name</td><td>User Role</td><td>IP Address</td><td>Last Activity</td></tr>";
foreach ($result as $row) {
$user_data=$row->user_data;
$final = array();
$str.="<tr>";
foreach (unserialize($user_data) as $k => $v) {
$final[] = array('key' => $k, 'value' => $v);
if($k=='username') {
$str.="<td>$v</td>";
}
if($k=='user_role') {
$str.="<td>$v</td>";
}
}
$str=$str."<td>$row->ip_address</td><td>".date('d/m/y : H:i:s',$row->last_activity)."</td></tr>";
}
$str=$str."</table>";
$data['users']=$str;
$this->load->view('admin_active_users',$data);
}
In model function:get_active_users()
function get_active_users() {
$this->db->where("user_data <>","");
$query = $this->db->get('re_ci_sessions');
return $query;
}
Am creating a web app in codeigniter, it retrieves posts from the database for a user based on the keywords they have added to their keyword list.
Am trying to retrieve all the posts with the users keywords but,it returns only one post whereas there are mutliple matches for the keywords in the posts
This is are the functions from my model
This function retrieves the users keywords
function user_keywords($user_id) {
//Get all the user keywords
$q = $this->db->select('keywords')
->from('keywords')
->where('U_id',$user_id)
->get();
$words = $q->result_array();
return $words;
}
This function retrieves the posts
function get_latest_pheeds() {
$this->load->helper('date');
$time = time();
$keyword = $this->user_keywords($this->ion_auth->user_id);
foreach($keyword as $word) {
$q = $this->db->select('user_id,pheed_id,datetime,pheed,COUNT(pheed_comments.comment_id) as comments')
->from('pheeds')
->join('pheed_comments','pheed_comments.P_id=pheeds.pheed_id','left')
->like('pheed',$word['keywords'])
->order_by('datetime','desc')
->get();
}
$rows = $q->result_array();
return $rows;
}
And my controller encodes it in JSON
function latest_pheeds() {
if($this->isLogged() == true) {
$this->load->model('pheed_model');
$data = $this->pheed_model->get_latest_pheeds();
echo json_encode($data);
}
return false;
}
I really appreciate the help
I think (but it is hard without testing) that the problem comes form the function get_last_feeds :
you query is built over each loop's iteration, but you fetch the results after. I think you get the results only for the last query (if you don't fetch the results on each loop, the next iteration overwrites the original request without fetching it's results).
I would make something like this :
<?php
function get_latest_pheeds() {
$rows = array(); // The final result, an array of rows
$this->load->helper('date');
$time = time();
$keyword = $this->user_keywords($this->ion_auth->user_id);
foreach($keyword as $word) {
$q = $this->db->select('user_id,pheed_id,datetime,pheed,COUNT(pheed_comments.comment_id) as comments')
->from('pheeds')
->join('pheed_comments','pheed_comments.P_id=pheeds.pheed_id','left')
->like('pheed',$word['keywords'])
->order_by('datetime','desc')
->get();
$rows[] = $q->result_array();
}
return $rows;
}