Display topic at top of list if has new reply - codeigniter

I have a list of my topics by default it will get the topics where the reply_id is 0 And then arrange them by there date_created.
How every if there is a reply to one of the topics then that topic should go to the top of the list.
Question How can I make sure if there is a new reply to a topic then that topic will go to list.
Currently my var dump as you can see have two items how ever the 2nd array item should be at top because it has a new last post time()
Array
(
[0] => Array
(
[title] => How to
[author] => demo
[author_post_time] => Tue Jun 13 , 2017 19:43:01 pm
[last_post_by] => demo
[latest_post_time] => Tue Jun 13 , 2017 19:43:01 pm
)
[1] => Array
(
[title] => How to install codeigniter
[author] => admin
[author_post_time] => Sat Jun 10 , 2017 23:26:48 pm
[last_post_by] => demo
[latest_post_time] => Tue Jun 13 , 2017 20:48:00 pm
)
)
Image of database
Model
<?php
class Topic_model extends CI_Model
{
public function get_active_topics($fid)
{
$data = array();
$this->db->select('t.*, u.username');
$this->db->from('topics t');
$this->db->join('user u', 'u.user_id = t.user_id');
$this->db->where('t.reply_id', '0');
$this->db->order_by('t.date_created', 'desc');
$query = $this->db->get();
foreach ($query->result_array() as $topic_result)
{
$reply = $this->get_reply($topic_result['topic_id']);
// This $date1 just for display only as shown on image
$date1 = date('D M d', $topic_result['date_created']) . ' , ' . date('Y H:i:s a', $topic_result['date_created']);
// This $date2 just for display only as shown on image
$date2 = date('D M d', $reply['date_created']) . ' , ' . date('Y H:i:s a', $reply['date_created']);
$data[] = array(
'title' => $topic_result['title'],
'author' => $topic_result['username'],
'author_post_time' => $date1,
'last_post_by' => isset($reply['username']) ? $reply['username'] : $topic_result['username'],
'latest_post_time' => ($reply['reply_id'] > 0) ? $date2 : $date1,
);
}
return $data;
}
public function get_reply($reply_id)
{
$this->db->select('t.*, u.username');
$this->db->from('topics t');
$this->db->join('user u', 'u.user_id = t.user_id');
$this->db->where('t.reply_id', $reply_id);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->row_array();
}
return false;
}
}

Please try to use below mentioned line, I hope this will fix your issue.
Change From
$this->db->order_by('t.date_created', 'desc');
TO
$this->db->order_by('t.reply_id DESC, t.date_created DESC');

Try ordering your table first by date2 and if that doesnt exist (no reply) then date1. You seem to have it implemented already, you're just ordering by date created on the post.

Related

Laravel9: How to let model's find() work?

I have service layer. My codes works in Laravel 5.6. Now I'm rewriting in Laravel 9, it doesn't work anymore.
UserController
public function getForm($id = null)
{
...
$user = $this->userService->findIdOrNew($id);
UserService
class UserService
{
public function __construct(Request $request)
{
parent::__construct();
$this->request = $request;
$this->modelName = "\App\Models\User";
$this->model = new $this->modelName;
$this->table = $this->model->getTable();
}
private function newModel()
{
return new $this->modelName;
}
public function findIdOrNew($id = null)
{
if(empty($id)){
$row = new $this->modelName;
}else{
$row = $this->model->find($id);
echo "<pre>", print_r($row, 1), "</pre>";exit;
}
return false;
}
Logic:
If no user id, then new an emtpy user model, return it.
If user id provided, then get the user model, and find the user id.
$this->model only do the new action in __controller.
I have many other functions like this.
public function updateById($data, $id)
{
$row = $this->model->find($id);
$row->email = $data['email'];
$row->name = $data['name'];
...
public function getRows($data = array(), $debug = 0)
{
$query = $this->model->query();
if(!empty($data['filter_ids'])){
$query->whereIn('id', $data['filter_ids']);
}
if(!empty($data['filter_name'])){
$words = explode(' ', trim(preg_replace('/\s+/', ' ', $data['filter_name'])));
$query->where(function ($query) use($words) {
$query->orWhere(function ($query2) use($words) {
foreach ($words as $word) {
$query2->where('name', 'like', "%{$word}%");
}
});
});
}
In this way, I don't use User::find(1), I don't need to say which model I want in functions. Just write it once in __contructor().
It really works in my laravel 5.6. Now it returns empty. No error message.
public function findIdOrNew($id = null)
{
ini_set("display_errors", "On");
error_reporting(E_ALL ^E_NOTICE ^E_DEPRECATED);
$row = $this->model->find($id);
echo "<pre>", print_r($row, 1), "</pre>";exit;
I should get:
App\Models\User Object
(
[fillable:protected] => Array
(
[0] => name
[1] => email
[2] => password
)
[hidden:protected] => Array
(
[0] => password
[1] => remember_token
)
[connection:protected] => mysql
[table:protected] =>
[primaryKey:protected] => id
[keyType:protected] => int
[incrementing] => 1
[with:protected] => Array
(
)
[withCount:protected] => Array
(
)
[perPage:protected] => 15
[exists] => 1
[wasRecentlyCreated] =>
[attributes:protected] => Array
(
[id] => 50
[rcode] => 1971836358
[name] => ooxxooxx
...
Now just a white page. What did I missed ?
I deleted all logs, restart apache server, then reload the page.
Apache/logs/laraocadmin9.test-access.log
127.0.0.1 - - [16/Jun/2022:14:39:46 +0800] "GET /en/admin/system/user/users/49/edit HTTP/1.1" 200 11
127.0.0.1 - - [16/Jun/2022:14:39:48 +0800] "GET /favicon.ico HTTP/1.1" 200 -
Apache/logs/laraocadmin9.test-error.log
(empty)
Apache/logs/access.log
(empty)
Apache/logs/error.log
[Thu Jun 16 14:38:09.392250 2022] [mpm_winnt:notice] [pid 40028:tid 388] AH00455: Apache/2.4.53 (Win64) mod_fcgid/2.3.10-dev configured -- resuming normal operations
[Thu Jun 16 14:38:09.393249 2022] [mpm_winnt:notice] [pid 40028:tid 388] AH00456: Apache Lounge VS16 Server built: Mar 16 2022 11:26:15
[Thu Jun 16 14:38:09.406444 2022] [mpm_winnt:notice] [pid 40028:tid 388] AH00418: Parent: Created child process 20972
[Thu Jun 16 14:38:10.096179 2022] [mpm_winnt:notice] [pid 20972:tid 432] AH00354: Child: Starting 64 worker threads.
Laravel storage\logs
only a file name .gitnore
Sorry, it still works. The user id I passed was wrong. I had two different projects. one is
$this->getForm('edit', $id)
$this->getForm('create', $id)
function getForm($action, $id=null)
another is
$this->getForm($id)
$this->getForm($id)
function getForm($id=null)
I got mixed up, I passed 'edit' to getForm($id)

Eloquent trying to get date with time

I'm trying to get all the reservations in a specific date and time and count the guests to find the available seats
What i'm doing in the controller:
public function getSeats() {
$data = request()->validate([
'date' => 'required',
'hours' => 'required',
'place_id' => 'required'
]);
$hours = [];
foreach($data['hours'] as $h) {
$date = $data['date'].' '.$h;
//Carbon date: 2021-08-31 08:00:00 | Database Date: 2021-08-31 08:00:00
$count = Reservation::where('place_id', $data['place_id'])->whereDate('date', Carbon::create($date)->toDateTimeString())->sum('guests');
$object = (object) [
'hour' => $h,
'guests' => $count
];
array_push($hours, $object);
}
}
It returns null, what am i doing wrong?
**Edit
I'm also using 24H in the time selector, so when i create a reservation at 12:00 in the morning eloquent grabs it as 00:00 in the night.
Using where instead of whereDate fixed the issue

How to Show Categories and multilevel Subcategories in Codeigniter Dropdown list

Hello Friends i am New in Codeigniter i have no Experience in any project i am making Shopping Website for Learning Purpose only not Real Project.When Creating Admin Panel I am Able to Fetch Categories and Subcategories tree using Loop but how to get these categories in Dropdown Menu in Tree format.
Like this-
Electronics
->Phones
->Tablets
->Mobiles
->Computer
->Laptops
->Desktops
Furniture
->Tables
->Plastic Table
->Wooden Table
My Model is :-
function getcategories($parent_id = 0) {
$categories = array();
$this->db->where('parentid',$parent_id);
$query = $this->db->get('categories');
$result = $query->result_array();
foreach ($result as $mainCategory) {
$category = array();
$category['id'] = $mainCategory['id'];
$category['categoryname'] = $mainCategory['categoryname'];
$category['parentid'] = $mainCategory['parentid'];
$category['sub_categories'] = $this->getcategories($category['id']);
$categories[$mainCategory['id']] = $category;
}
return $categories;
}
My Categories array is Look like this:-
Array
(
[category] => Array
(
[1] => Array
(
[id] => 1
[categoryname] => Electronics
[parentid] => 0
[sub_categories] => Array
(
[2] => Array
(
[id] => 2
[categoryname] => Smartphones
[parentid] => 1
[sub_categories] => Array
(
[4] => Array
(
[id] => 4
[categoryname] => Sony
[parentid] => 2
[sub_categories] => Array
(
)
)
)
)
[3] => Array
(
[id] => 3
[categoryname] => Televisions
[parentid] => 1
[sub_categories] => Array
(
)
)
)
)
)
)
my database table look like this:-
it is my database table
This code works:
function getcategories($parent_id = 0) {
$categories = array();
$category = array();
$subcategories = array();
$q = $this->db->get_where('categories', array('parent_id' => $parent_id));
$results = $q->result();
foreach ($results as $mainCat) {
$q2 = $this->db->get_where('categories', array('parent_id' => $mainCat->id));
$results2 = $q2->result();
foreach ($results2 as $key => $subCat) {
$subcategory['id'] = $subCat->id;
$subcategory['name'] = $subCat->name;
$subcategory['parentid'] = $subCat->parent_id;
$subcategories[$subCat->id] = $subcategory;
}
$category['id'] = $mainCat->id;
$category['name'] = $mainCat->name;
$category['parentid'] = $mainCat->parent_id;
$category['subcat'] = $subcategories;
$categories[$mainCat->id] = $category;
$subcategories='';
}
return $categories;
}

codeignite trying to get property of non-object not resolved

I am attempting to access the result set from a model query in the view. I have the following:
Controller:
$courseId = $this->session->userdata('courseId');
//echo "Course: ".$courseId;
if(isset($courseId) && $courseId != '')
{
$result = $this->Course_model->loadBasicDetailsEdit($courseId);
$data['basicCourseDetails'] = $result;
$this->load->view('course/basicDetails', $data);
}
Model:
function loadBasicDetailsEdit($courseId)
{
$this->db->select('*');
$this->db->where('course_id', $courseId);
$this->db->from('course');
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
return $query->result();
} else {
return FALSE;
}
}
and in the view I tried to print_r() and got this:
Array ( [0] => stdClass Object ( [course_id] => 8 [title] => Photography [summary] => [description] => [price] => [member_id] => 12 [category] => [audience] => [goals] => [date] => 2013-09-26 [production] => 0 ) )
I tried to access this using $basicCourseDetails->title or $basicCourseDetails['title']
but neither are working. Any hint as to why this is happening?
Regards,
try this:
foreach($basicCourseDetails as $basic){
echo($basic->title);
}
or something like this:
echo($basicCourseDetails[0]->title);
This is an array of objects
Array ( [0] => stdClass Object ( [course_id] => 8 [title] => Photography [summary] => [description] => [price] => [member_id] => 12 [category] => [audience] => [goals] => [date] => 2013-09-26 [production] => 0 ) )
Contains one stdObject in the array, so, first objects is 0, if there were more, then second item could have index 1 and so on. To retrieve data from the first (here is only one) stdobject you may use
echo $basicCourseDetails[0]->title; // title will be printed
You can send data to the view page by this line of code which is mentioned in above question.
$result = $this->Course_model->loadBasicDetailsEdit($courseId);
$data['basicCourseDetails'] = $result;
$this->load->view('course/basicDetails', $data);
But when you will access these data in view then you need to access all data one by one by using foreachloop in the view page.
For example if you have a view page like basic_details.php inside course folder then you need to write code like this to access these data.
foreach ($basicCourseDetails as $key => $value) {
$name = $value->name;
}
The above foreachloop can be written in view page where you want to access data.

Retrieve data from database as a set of rows indexed by primary key in CodeIgniter

I have a table like this:
id | username | email
---+----------+----------------
1 | John | john#example.com
17 | Mary | mary#example.com
And I want to get a result like this:
array(
1 => array(
username => 'John',
email => 'john#example.com'
),
17 => array(
username => 'Mary',
email => 'mary#example.com'
)
);
Is it possible to do with built-in functions in CodeIgniter?
Answering my own question:
I've created a helper:
function assoc_by($key, $array) {
$new = array();
foreach ($array as $v) {
if (!array_key_exists($v[$key], $new))
$new[$v[$key]] = $v;
}
return $new;
}
Which can be used like this:
$rows = assoc_by('id', $this->db->get_where(...)->result_array());
to the best of my knowledge there no built in functions for the same, though you can create a base model, extend it and create a function for the same,
<?php
//Assuming $dbdata is the data returned as an array from database
$result = array();
if(!empty($dbdata))
{
foreach($dbdata as $key=>$value)
{
$id = $value['id'];
$result[$id] = array( 'username' => $value['username'],
'email'=>$value['email'];
);
}
return $result;
}
?>

Resources