Cannot join 3 table in Codeigniter - codeigniter

I am retrieving products from codeigniter there are three tables:
dg_products
dg_rating
dg_like
After joining dg_products and dg_rating is working but I want to get the like status from dg_like.
Structure of dg_like is:
id | P_id | Uid
From session I am able to retrieve current logged in user id but cannot retrieve whether that user has liked that particular product or not. Please give any suggestions.
public function get_featured()
{
$this->db->select('dg_products.*, AVG(dg_rating.rating) As averageRating');
$this->db->from('dg_products');
$this->db->join('dg_rating', 'dg_products.id = dg_rating.product_id','left');
$user_info=$this->session->userdata('logged_in');
$user_id=$user_info['id'];
if($user_id != '') {
$this->db->join('dg_like', 'user_id = dg_like.u_id');
}
$this->db->where('dg_products.is_featured_prod','1');
$this->db->group_by("dg_products.id");
$query = $this->db->get();
$result = $query->result();
return $result;
}

According to the info you provide, you're joining using a non-existing field
If dg_like's structure is
id | P_id | Uid
the join statement should be
$this->db->join('dg_like', 'user_id = dg_like.Uid');
I'd go even further and recommend you make it a LEFT JOIN so the output of the query contains all rows, regardless of being liked or not:
$this->db->join('dg_like', 'user_id = dg_like.Uid', 'LEFT');
hope that works

If you retrieve current logged in user record, according to your table dg_like structure is id | P_id | Uid. Here, $user_id is login user id.
$this->db->select('dg_products.*, AVG(dg_rating.rating) As averageRating');
$this->db->from('dg_products');
$this->db->join('dg_rating', 'dg_products.id = dg_rating.product_id','left');
if($user_id != '') {
$this->db->join('dg_like', 'dg_products.id = dg_like.P_id');
}
$this->db->where('dg_like.Uid',$user_id);
$this->db->where('dg_products.is_featured_prod','1');
$this->db->group_by("dg_products.id");
$query = $this->db->get();
$result = $query->result();
I hope your issue is resolved.

Related

How to get data from 2 related tables in the same controller in codeigniter?

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.

CodeIgniter querybuilder convert query no results

I'm trying to convert a query to CodeIgniter's query builder.
Original version:
$query = $this->db->query('SELECT tb.*,b.`property` FROM `email_template_blocks` as tb inner join email_blocks as b on tb.`block_id`=b.`id` where tb.template_id=' . $id);
if ($query->num_rows() < 1) {
return null;
}
return $query->result_array();
Query builder version:
$this->db->select('*');
$this->db->from('email_template_blocks');
$this->db->join('email_blocks', 'email_template_blocks.block_id = email_blocks.id', 'inner');
$this->db->where('email_template_blocks.template_id', $id);
$query = $this->db->get();
//$query = $this->db->query('SELECT tb.*,b.`property` FROM `email_template_blocks` as tb inner join email_blocks as b on tb.`block_id`=b.`id` where tb.template_id=' . $id);
if ($query->num_rows() < 1) {
return null;
}
return $query->result_array();
The query builder version returns no results (no error messages either and I have db debug on). I'm fairly certain I'm doing something wrong, but I find the CI documentation on joins lacking. How can I fix this?
I'd also like to know how to select all of the items from the email_template_blocks table and just join the property column of the email_blocks table.
Email template blocks table:
table schema
Email blocks table:
table schema

Laravel 5 updateOrCreate (or Delete)

I have a setup where, I have a user_roles table.
Then the administrator, will be able to update these, by adding new role, updating the name of an old role, and lastly delete.
------------------
| id | user_role |
| 1 | admin |
| 2 | role 1 |
| 3 | role 3 |
------------------
I tried to use this block of code to update, add, delete the roles
public function update(Request $request, $id){
$roles = Model::all();
foreach($roles as $role){
$role->delete();
}
foreach($request->role as $role){
$role = new Model;
$role->user_role = $role;
$role->save();
}
}
But in the users table, I have a user_role column that references to the id of the user_roles table, so whenever I use the above code, all rows will be deleted, then a new id will be created for the new rows inserted. So, when I go back to the list of users, their user_role column will return null, because each user has a non-existing user_role id.
Using updateOrCreate kind of solves my problem, when it comes to updating old row/s or creating new row/s but the problem is, deleting rows. It can't delete rows.
I need to delete the rows that are existing in the database, and missing in the request.
What would be the best way to do this ?
I have fixed this case using the id approach proposed by maslauskast # https://laracasts.com/discuss/channels/laravel/updateorcreate-rows-from-a-csv-or-delete-if-not-on-the-csv?page=0
In your case a solution* will be
public function update(Request $request, $id){
$usersRoleToDelete = Model::all()->pluck('id', 'id');
foreach($request->role as $role) {
$createdOrUpdated = Model::createOrUpdate(['user_role' => $role]);
if (!empty($usersRoleToDelete[$createdOrUpdated->id])) {
unset($usersRoleToDelete[$createdOrUpdated->id]);
}
}
if (count($usersRoleToDelete)) {
Model::whereRaw(sprintf('id IN (%s)', implode(',', $usersRoleToDelete)))->delete();
/* Alternatively you could use
* Model::whereIn('id', $usersRoleToDelete)->delete();
* if the amount of ids is smaller than the maximum PDO arguments allowed
*/
}
}
Please note that I have not tested this.
this is my working updateOrCreate method based on Adrian answer in Laravel 5.3
public function update($id, Request $request)
{
$et=Model::find($id);
//update some parent table field's (if you want)
$et['type']=$request['type'];
$et['sum'] =preg_replace('/[^0-9]/s', '', $request['sum']); //for remove thousand separtor
$et->save();
$et_det=$et->et_dets()
->pluck('id','id'); // one-to-many relation
for ($i=0;$i<count($request['det_id']);$i++)
{//some matching condition
$createdOrUpdated = Model_dets::updateOrCreate(
[
'parent_id'=>$id,
'total'=>$request['total'][$i]
],
[
'columnA' => $request['columnA'][$i],
'ColumnB' => $request['ColumnB'][$i])
]);
if (!empty($et_det[$createdOrUpdated->id])) {
unset($et_det[$createdOrUpdated->id]);
}
}
if (count($et_det)) {
Model_det::whereIn('id', $et_det)->delete();
}
return Redirect::to('index')->with('alert-success','Update successfully');
}

Raw SQL inside eloquent query

I have a users table, roles table and a user_role table.
User
id | name
Roles
id | title
User_Role
user_id | role_id
I need an eloquent query that finds if a user has all roles.
So far I have:
$userId = 1;
$role = array('admin', 'public');
$data = User::whereHas('roles', function($q) use ($role){
$q->whereRaw($q->whereIn('title', $role)->count() .' = '.count($role));
})->find($userId);
But I get the error:
Unknown column user.id in where clause.
Where am I going wrong?
This should work.
The query should return null if the user doesn't have the specified roles.
$userId = 1;
$role = array('admin', 'public');
$data = User::whereHas('roles', function($q) use ($role){
$q->whereIn('title', $role);
}, '>=', count($role))->find($userId);

Codeigniter, how to pass COUNT result too my view

i have problem with passing data from model to my view. In Database i have Project with a few tasks i need to COUNT it. My problem is: How to pass the results to the view with foreach.
(echo $this->db->count_all_results(); in MODEL show good results)
Project 1: 5 tasks
Project 2: 10 tasks
Project 3: 1 task
MODEL:
function wyswietl($arrayid){
$query = $this->db->query("SELECT COUNT( id_zadania ) AS zlicz
FROM projekty_zadania
WHERE id =$arrayid");
return $query->result();
CONTROLLER
function WszystkieProjekty(){
$data['moje'] = $this->Todo_model->wyswietlWszystkieProjekty();
$arrayid = array();
foreach( $data['moje'] as $row ){
$row->id;
$aaa = $row->id;
$arrayid[] = $this->Todo_model->wyswietl($aaa);
}
$data['tabid'] = $arrayid;
$this->load->view('Projekty.html', $data);
}
MODEL:
function wyswietlWszystkieProjekty(){
$query = $this->db->query("SELECT * FROM todo");
return $query->result();
}
You're passing back to your controller a result set, so all you need to do is iterate over the result set, generating actual rows. It's not too hard, and you've got the right idea.
You have:
function wyswietl($arrayid){
$query = $this->db->query("SELECT COUNT( id_zadania ) AS zlicz
FROM projekty_zadania
WHERE id =$arrayid");
return $query->result();
As your model function that is supposed to return the count, right? Easiest way to do this is right from the model to keep your controller from having to do the legwork. When you run the count function in mysql, you'll only get back one row in your case, so using num_rows() isn't going to help because this query will always generate 1 row.
function wyswietl($arrayid){
$query = $this->db->query("SELECT COUNT(id_zadania) AS zlicz
FROM projekty_zadania
WHERE id =$arrayid");
$rs = $query->result();
return $rs[0]['COUNT(id_zaedania)'];
}
In your query, you have counted the data, so i think you can get the total data in the model from $query->rows()->zlics. And in the controller, just pass it to the view like usual
$data['moje'] = $this->Todo_model->wyswietlWszystkieProjekty(); $this->load->view('Projekty.html', $data);

Resources