I'm trying to get data from 2 DB tables that are related. Departments and Functions: Each Department has multiple Functions.
I want to show all data in an accordion on the same page.
Until now, the code works like this:
Declare the variable departments in the controller, and in view, in the foreach loop, I have called the Functions model in a variable.
Controller:
public function index(){
//Data variable declarations
$data['page_title'] = "Departments and Functions";
$data['page_subtitle'] = "choose an occupation for the list of users assigned";
//Data variable declaration - from models
$data['departments'] = $this->Department->get_all('departments');
$this->load->view('layouts/header');
$this->load->view('layouts/title', $data);
$this->load->view('layouts/aside');
$this->load->view('departments/index', $data);
$this->load->view('layouts/footer');
}
Here I want to add the Function->get_by_department_id() method. How to get the ID dynamically?
The occupation model methond:
public function get_by_fk($table = 'occupations', $fk = "department_id" , $fk_value=$department->department_id){
$this->db->select('*');
$this->db->from($table);
$this->db->where($fk, $fk_value);
$query = $this->db->get();
return $result = $query->result();
}
Try using a left join
function get_departments_and_functions() {
$sql = 'SELECT `deptartments`.*, `functions`.*
FROM `departments` LEFT JOIN `functions`
ON `functions`.`deptartments_id` = `departments`.`id`';
return $this->db->query($sql)->result();
}
You could also query the departments and then foreach over the departments and query to get the functions. Then you would manually build the result set.
i am new in CI i have a data the result from a process and i want to additional information on that from difretnt table like this picture.
both table are linked to an id (idhn). i make query join in model like this
function gabung(){
$this->db->select('*');
$this->db->from('metode');
$this->db->join('hasil_inden','hasil_inden.idhn=metode.idhn');
$query = $this->db->get();
return $query->result();
}
i called $metode in controller like this
' $metode = $this->Proses_model->gabung();'
but it is not work undefined variablev $metode please give me solution to fix it
Good Day Masters,
Can anyone help me how to convert this SQL Query into Code Igniter format (model).
SELECT firstName, FLOOR(DATEDIFF(CURRENT_DATE, birthDate)/365.25) as age FROM residents_tbl WHERE FLOOR(DATEDIFF(CURRENT_DATE, birthDate)/365.25) >= 18
I don't know how to write it on WHERE clause.
$query = $this->db->select('*');
$query = $this->db->from('residents_tbl');
**$query = $this->db->where('isHead', '1');**
$query = $this->db->order_by('lastName', 'ASC');
$query = $this->db->get('', 15, $this->uri->segment(3));
if ($query->num_rows() > 0) {
return $query->result();
}
TIA.
This is a simplified version with chaining. I just changed the type of 1 from string to number which might caused the problem.
$query = $this->db
->where('isHead', 1)
->get('residents_tbl')
->order_by('lastName', 'ASC');
I am using codeigniter 3.1.0 and I am trying to get the total SUM of two columns from different tables
If my user_id = 1 it should return the total sum of 421 but returns 431 It is adding the votes from other users on my reply table
Question Using Active Record How can I make sure the SUM is getting the correct amount for the users id.
Model Function
public function thread_reputation($user_id) {
$this->db->select('SUM(reply.votes + thread.votes) AS reputation');
$this->db->from('thread', 'left');
$this->db->join('reply', 'reply.user_id = thread.user_id', 'left');
$this->db->where('thread.user_id', $user_id);
$this->db->where('reply.user_id', $user_id);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->row();
} else {
return 0;
}
}
Controller section where i echo it
$thread_reputation = $this->thread_analytics_model->thread_reputation('1');
echo $thread_reputation->reputation;
Thread Table
Reply Table
Change your query with this
$query = $this->db->query("SELECT SUM(A.votes) as reputation from
(
SELECT reply.votes FROM reply where reply.user_id = $user_id
UNION ALL
SELECT thread.votes FROM thread where thread.user_id = $user_id
)AS A");
Tested and properly working
Check Screenshot:-
Query using ACTIVE REOCRD
$this->db->select("SUM(A.votes) as reputation");
$this->db->from("(
SELECT reply.votes FROM reply where reply.user_id = $user_id
UNION ALL
SELECT thread.votes FROM thread where thread.user_id = $user_id) AS A");
$query = $this->db->get();
Another Solution using $this->db->get_compiled_select();
public function reputation($user_id) {
$this->db->select('thread.votes');
$this->db->from('thread');
$this->db->where('thread.user_id =' . $user_id);
$thread_query = $this->db->get_compiled_select();
$this->db->select('reply.votes');
$this->db->from('reply');
$this->db->where('reply.user_id ='. $user_id);
$reply_query = $this->db->get_compiled_select();
$query = $this->db->query("SELECT SUM(total.votes) as reputation from ($reply_query UNION ALL $thread_query) as total");
if ($query->num_rows() > 0) {
return $query->row();
} else {
return 0;
}
}
When you will use left join, it will return matched column & all other unmatched column from left table. Use inner join & check your result.
It seems Laravel pagination does not working properly with group by clause. For example:
$users = Subject::select(DB::raw('subjects.*, count(user_subjects.id) as total_users'))
->join('user_subjects', 'user_subjects.subject_id', '=', 'subjects.id')
->whereNull('user_subjects.deleted_at')
->groupBy('subjects.id')
->orderBy('subjects.updated_at', 'desc')
->paginate(25);
Produced
select subjects.*, count(user_subjects.id) as total_users
from `subjects` inner join `user_subjects` on `user_subjects`.`subject_id` = `subjects`.`id`
where `subjects`.`deleted_at` is null and `user_subjects`.`deleted_at` is null
group by `subjects`.`id`
order by `subjects`.`updated_at` desc
note that, there is no limit clause on the query.
Working fine if no group by clause in the query:
$users = Subject::select(DB::raw('subjects.*, count(user_subjects.id) as total_users'))
->join('user_subjects', 'user_subjects.subject_id', '=', 'subjects.id')
->whereNull('user_subjects.deleted_at')
->orderBy('subjects.updated_at', 'desc')
->paginate(25);
produced the following query:
select subjects.*, count(user_subjects.id) as total_users from `subjects`
inner join `user_subjects` on `user_subjects`.`subject_id` = `subjects`.`id`
where `subjects`.`deleted_at` is null and `user_subjects`.`deleted_at` is null
order by `subjects`.`updated_at` desc
limit 25 offset 0
does anyone has any idea how can i fix this?
Check the documentation
https://laravel.com/docs/5.2/pagination
Currently, pagination operations that use a groupBy statement cannot
be executed efficiently by Laravel. If you need to use a groupBy with
a paginated result set, it is recommended that you query the database
and create a paginator manually.
I know it is an old question, by I am sharing my solution for future reference.
I managed to write a function based on this link which does the heavy job of determining the pagination of a complex query. Just pass the 'QueryBuilder' and it will return the paginated object/collection.
Additionally, this procedure can track and maintain the other parameters except for page=.
public function mergeQueryPaginate(\Illuminate\Database\Eloquent\Builder $query): \Illuminate\Pagination\LengthAwarePaginator
{
$raw_query = $query;
$totalCount = $raw_query->get()->count();
$perPage = request('per-page', 10);
$page = request('page', 1);
$skip = $perPage * ($page - 1);
$raw_query = $raw_query->take($perPage)->skip($skip);
$parameters = request()->getQueryString();
$parameters = preg_replace('/&page(=[^&]*)?|^page(=[^&]*)?&?/', '', $parameters);
$path = url(request()->getPathInfo() . '?' . $parameters);
$rows = $raw_query->get();
$paginator = new LengthAwarePaginator($rows, $totalCount, $perPage, $page);
$paginator = $paginator->withPath($path);
return $paginator;
}
This works for me in laravel 5.2
Select(\DB::RAW("assignment_descendant_child.assignment_descendant_child_id, assignment_descendant_child.assignment_descendant_child_name, COUNT(assignment_descendant.assignment_descendant_id) as xNum"))
->leftJoin(
'assignment_descendant',
'assignment_descendant.assignment_descendant_child_id',
'=',
'assignment_descendant_child.assignment_descendant_child_id'
)
->orderBy('assignment_descendant_child_name')
->groupBy('assignment_descendant_child.assignment_descendant_child_id')
->paginate(\Config::get('constants.paginate_org_index'))
create a database view namedvw_anything. MySql query will be like
create view vw_anything as select subjects.*, count(user_subjects.id) as total_users from subjects inner join user_subjects on user_subjects.subject_id = subjects.id
where subjects.deleted_at is null and user_subjects.deleted_at is null group by subjects.id;
Now create a new model named UserSubModel for this view, protected $table = 'vw_anything';
Now your paginate query will be like UserSubModel::orderBy('subjects.updated_at', 'desc')->paginate(25);
.
To answer this questioin Laravel Pagination group by year and month only
View query will be :
create view vw_anything as select gallery.*, DATE_FORMAT(created_at, "%Y-%m") as tanggal,count(created_at) as jumlah from gallery group by tanggal;
Let you model is VwModel then your paginate query will be
VwModel::where('type','Foto')->orderBy('tanggal','desc')->paginate(2);
This works if you want to group by and paginate.
$code = DB::table('sources')
->select(DB::raw('sources.id_code,sources.title,avg(point) point'))
->join('rating','sources.id_code','rating.id_code')
->groupBy('sources.id_code')
->groupBy('sources.title')
->groupBy('sources.language')
->groupBy('sources.visited')
->paginate(5);