So I trying to build a notification system (CodeIgniter) and not store it in my database by this unique ID. Now I got some problem to using `SELECT query.
Also this is array stored in "value" row:
[{"id":0,"user_id":"1","comment":"That's a Nice Video.","posttime":1403523177,"status":1},{"id":1,"user_id":"4","comment":"Nice to see this..!!","posttime":1403590409,"status":1}]
And this is my (not work) query:
$query = $this->db->get_where('post_meta',array('status'=>1),in_array('user_id', $id));
Ideas?
Note: Notification will be sparated by "user_id".
You should not use in_array('user_id', $id) on that function because it returns boolean.
On the active record page: https://ellislab.com/codeigniter/user-guide/database/active_record.html you can take a look at parameter it takes for get_where() function
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
Notice how the third parameter takes $limit which talks about the number of data you'll receive. (Leaving this blank will return you all data).
Some code examples:
If you just want to get the data with status = 1, use the following:
$query = $this->db->get_where('post_meta',array('status'=>1));
If you want to get the data with status = 1 and user_id = $id, use the following:
$this->db->like('value', '"user_id":"'.$id.'"');
$query = $this->db->get_where('post_meta',array('status'=>1));
The solution above is not the best, but it should work.
The $this->db->like() function will create rules to get data in value row which has "user_id":"$id" where $id is the value that you define.
What if I want to get all notifications and group them based on their ID?
I usually get all the data and then use PHP to group them into its own array. I think it's cheaper than relying on database to do that (Correct me if i'm wrong).
So use the first code:
$query = $this->db->get_where('post_meta',array('status'=>1));
Then iterate them using foreach() or whatever you find convenient.
$data = array();
foreach($query as $k=>$v) {
// Run a function to get User ID
$user_id = your_function_here($v->value);
if(!isset($data[$user_id]))
$data[$user_id] = array();
// This is just some example to group them together, you can optimize it to your own liking
array_push($data[$user_id],$v);
}
your_function_here() is your function to get the user_id from value row on your database.
Related
I've been trying this query
Model::find()
->innerJoin('TranslationTable', 'TranslationTable.model_id = Model.id')
->where(['IN', 'translation_code', $arrayOfTranslationCodes])
->asArray()
->all();
The translation table contains multiple rows with the same ID but with different translation codes.
This query only returns the first matching locale for a given ID. How would I retrieve the other translation codes for a given ID?
This is the solution that I came to:
$query = Model::find()
-> innerJoin('TranslationTable', 'TranslationTable.model_id = Model.id');
foreach ($arrayOfTranslationCodes as $translation)
{
$query->andWhere(['OR', 'translation_code', $translation])
}
$queryResponse = $query->asArray()->all();
This allowed me to find rows with the same id, but have different translations. You need to store the $query->asArray()->all(); as $query itself just returns the active query.
I have the following table named mytable:
id SERIAL PK
namae VARCHAR
And using laravel 5.7 I need to retrieve the data using the following code (tested in a tinker session):
$yakuzaNames = DB::select('SELECT id from mytable where name like 'omaewa%');
dump($yakuzaNames);
The problem is that once data retrieved in variable $yakuzaNames is in the following format:
[ { id: 1},{id:2},...]
From the results I need to retrieve an array containing integers with the id, therefore I need to manipulate it via array_map:
$yakuzaNames = DB::select('SELECT id from mytable where name like 'omaewa%');
$yakuzaNames = array_map(function($item){ return $item->id },$yakuzaNames);
Or use a foreach loop:
$yakuzaNames = DB::select('SELECT id from mytable where name like 'omaewa%');
$names = [];
foreach($yakuzaNames as $yakuzaName){
$names[] = $yakuzaName->id;
}
But using a loop seems kinda a waste also using some sort of iteration seems waste as well. Is there a way for laravel's database layer be able to return directly the data in the format I want to?
Use pluck method for collection. https://laravel.com/docs/8.x/collections#method-pluck
I have an sql request:
$listUsers=$connection->prepare("SELECT u.id as userid From user u , account a where (a.id_parent=$id_account OR a.id=$id_account) and u.id_account=a.id ");
$listUsers->execute();
$users=$listUsers->fetchColumn();
but fetchColumn return just one result, and I want a set of list user id to use it in the next request.
$listPush=$connection->prepare("select id from Table_name where id_user in (?));
$listPush->bindValue(1, $users);
$listPush->execute();
$idpushs=$listPush->fetchColumn();
but this return just one result. Any Idea to replace fetchColumn by other request or using doctrince.
With your logic, you can simply fetch all your users and implode it.
$listUsers=$connection->prepare("SELECT u.id as userid From user u , account a where (a.id_parent=$id_account OR a.id=$id_account) and u.id_account=a.id ");
$listUsers->execute();
$users=$listUsers->fetchAll();
$userIds = array();
foreach ($users as $user) {
$userIds[] = $user['userid'];
}
$users = implode(',', $userIds); //that hurts me so hard to code like this with symfony :'(
Fetch colum will only return the column of the next row. So for your second piece of code, you can loop over results.
But, if you're are using a framework like symfony, you have many other ways to make it cleaner. Just check out the symfony doc to use repository relations and more generally doctrine
I am using PDO to connect to my tables in the database. So I wrote a quick function to return the results that was return from the data table. Yes I can use SORT BY in my query to sort the results but i want to avoid that in this query because this query pull information for a large table.
* First I need to be able to sort this data set at the user end. so I need somehow to sort by different columns so I can sort by column "fullName" or sort by "userID" or "createdDate"
so when PDO fetch the results and return the array I want to sort those.
* Second question where in this function I do a free results or do I free them outside the query?
function getDataSet($query, $connection){
$cmd = $connection->query( $query );
return $cmd->fetchAll(); //PDO::FETCH_ASSOC
}
then I can call this function by simply doing
$dataset = getDataSet("select * from users", $db)
in my first question i want to sort $dataset.
I do NOT agree with you on not using "ORDER BY" in your SQL statement. But anyway, you can try this:
$tmp_dataset = array();
foreach($dataset as $data)
{
$tmp_dataset[ $data['name_of_column'] ] = $data;
}
$dataset = $tmp_dataset;
ksort($dataset);
In my CodeIgniter project I'm getting the list of projects and successfully output them on a page. However, the data in one of the columns on that page should be retrieved from a different table in DB using the project ID. Could anybody help me to figure out how that can be done? Basically I need to make another query to that other table specifying the project id but don't actually know how to do that with CodeIgniter.
UPDATE
In the model I'm getting the list of projects with the following function:
function get_projects_list($page, $limit){
$sql = sprintf("SELECT * FROM Project WHERE deleted != 1 LIMIT %d, %d", ($page-1)*$limit, $limit);
$query = $this->db->query($sql);
return $query->result();
}
And in the controller I call the following function:
$projects_list = $this->Project_management_model->get_projects_list($curPage, self::$LIMIT_PER_PAGE);
$data['projects_list'] = $projects_list;
$data['cur_page'] = $curPage;
$data['page_count'] = $pageCount;
$this->load->view('project_management_view', $data);
And in the view I simply run on the $data with foreach and list the results in a table. In that table there's a column where I need to show a result from another table based on the ID of the project of that very row.
Thanks for helping.
You didn't mention whether you are using ActiveRecord or not. I am assuming that you are. I'll also guess that maybe what you need to do is use a JOIN.
If you were using straight SQL, you would do this using some SQL that might look something like this:
SELECT a.appointment_time, u.user_real_name FROM appointment a, site_user u WHERE u.site_user_id = a.user_id;
That would pull the user's name from the user table based on the user id in the appointment table and put it with the appointment time in the query results.
Using ActiveRecord, you would do something like this:
$this->db->select('appointment_time,user_real_name')->from('appointment')->join('site_user', 'site_user_id=appointment_user_id');
But why don't you tell us a little bit more about your question. Specifically, do you want this column in the other table to be related to the rows from the first table? If so, my JOIN suggestion is what you need.
I've actually found a way to do that with a custom helper. Creating a new helper and loading it in the controller gives an option to use the function from that helper in the view.
Thanks.
public function get data()
{
$this->db->flush_cache();
$query = $this->db->get('project_table');
$result = $query->result();
$data = array();
for ($i = 0;$i < count($result);$i++)
{
$data[$i] = $result[$i];
$data[$i]['project_data'] = temp($result[$i]->id);
}
return data;
}
private function temp($id = 0)
{
$this->db->flush_cache();
$this->where('id',$id);
$query = $this->db->get('project_table2');
$result = $query->result();
if (count($result) != 0)
return $result[0]->data;
}
you can do it by some thing like that,or you can use sub-query by query function of database.