Querying 4 tables with inner join codeigniter - codeigniter

i have 4 tables jobs, company, employment_type & job_category the primary key for each are job_id, com_id, type_id, job_cat_id, but (com_id, type_id, job_cat_id) are foreign key to jobs table.
my query without active record work perfectly and it is as follow
select company.com_id, company.company_name, jobs.job_id, jobs.title, jobs.opening_date, jobs.closing_date, jobs.number_of_pos, employment_type.type_id, employment_type.type, job_category.job_cat_id, job_category. category from company inner join jobs on company.com_id=jobs.com_id inner join employment_type on employment_type.type_id=jobs.type_id inner join job_category on job_category.job_cat_id=jobs.job_cat_id
but if i try to use codeiginiter active record such as
$this->db->select('company.com_id, company.company_name, jobs.job_id, jobs.title, jobs.opening_date, jobs.closing_date, jobs.number_of_pos, employment_type.type_id, employment_type.type, job_category.job_cat_id, job_category. category');
$this->db->from('company');
$this->db->join('jobs','company.com_id=jobs.com_id','inner');
$this->db->join('employment_type', 'employment_type.type_id=jobs.type_id','inner');
$this->db->join('job_category', 'job_category.job_cat_id=jobs.job_cat_id','inner');
$this->db->order_by('job_id','DESC');
$this->db->limit($limit, $offset);
$query = $this->db->get();
return $query->result_array();
i end up with the following error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '`) INNER JOIN `jobs` ON `company`.`com_id`=`jobs`.`com_id` INNER JOIN `employmen' at line 1
SELECT `company`.`com_id`, `company`.`company_name`, `jobs`.`job_id`, `jobs`.`title`, `jobs`.`opening_date`, `jobs`.`closing_date`, `jobs`.`number_of_pos`, `employment_type`.`type_id`, `employment_type`.`type`, `job_category`.`job_cat_id`, `job_category`.` category FROM (`company`) INNER JOIN `jobs` ON `company`.`com_id`=`jobs`.`com_id` INNER JOIN `employment_type` ON `employment_type`.`type_id`=`jobs`.`type_id` INNER JOIN `job_category` ON `job_category`.`job_cat_id`=`jobs`.`job_cat_id` ORDER BY `job_id` DESC LIMIT 10
Any help would be appreciated

you have a space in job_category. category remove that and you should be golden

Format your query like this
$data = array(
'company.com_id',
'company.company_name',
'jobs.job_id',
'jobs.title',
'jobs.opening_date',
'jobs.closing_date',
'jobs.number_of_pos',
'employment_type.type_id',
'employment_type.type',
'job_category.job_cat_id',
'job_category.category'
);
$this->db->select($data);
$this->db->from('company');
$this->db->join('jobs','company.com_id=jobs.com_id','inner');
$this->db->join('employment_type', 'employment_type.type_id=jobs.type_id','inner');
$this->db->join('job_category', 'job_category.job_cat_id=jobs.job_cat_id','inner');
$this->db->order_by('job_id','DESC');
$this->db->limit($limit, $offset);
$query = $this->db->get();
return $query->result_array();

Related

How to sort with COUNT laravel eloquent relations between 3 tables

I have the following function that lists the Leads and the pages, I am asked to sort it by the activities but I have the problem that this is from another table if I do it in SQL mode I get the result, but with the actual writing of the code I don't get it.
This is my query, it has join with contacts and a left join with activities, the problem is that I only need to be able to sort it by activities.
SELECT l.id,l.status_id,l.user_id,l.created_at,l.ticket_id,l.last_lead, c.full_name, COUNT(a.lead_id) as total FROM `leads` l join contacts c on l.contact_id = c.id left join activities a on a.lead_id =l.id where active=1 and status_id=7 and project_id in (8,9,10,11) GROUP by l.id order by total desc;
And this is my eloquent query:
Order by comments.
if ($sortField == 'last_comment') {
$user = User::withRole(['salesman'])->pluck('id');
$sortField = Comment::select('created_at')
->whereColumn('comments.lead_id','leads.id')
->where('comments.user_id',implode(',',$user->toArray()))
->latest()
->take(1);
}
$leads_ = $this->leads
->openedStage() // where status_id = 7
->ticketActive() // where active = 1
->searchTickets($projects)
->orderBy($sortField,'desc')
->paginate((int)$per_page);
Where the following methods mean:
**openedStage()**: where status_id = 7
**ticketActive()**: where active = 1
**searchTickets($projects):
whereHas('contacts', function ($q) use ($projects){
$q->whereIn('project_id',$projects->toArray());
});

How to convert Sql query to codeigniter Active Record

I have sql query as below, i need to convert sql to codeigniter active record.
select * from color c
left join (select pc.* from product_color pc
LEFT join product p on pc.product_id=p.product_id
WHERE p.product_id=1)x on c.id=x.color_id
In codeigniter you can get compiled query using get_compiled_select function.
Let's create inner query first.
$inner_query = $this->db->select('pc.*')
->from('product_color pc')
->join('product p','pc.product_id = p.product_id','left')
->where('p.product_id',1)
->get_compiled_select();
Now we will use inner query to create our final query.
$final_query = $this->db->select('*')
->from('color c')
->join("($inner_query) x",'c.id=x.color_id','left')
->get_compiled_select();
echo $final_query; die;
Try this into model file. and it's always better to keep sql keywords in capital.
$query = "SELECT * FROM color c
LEFT JOIN (SELECT pc.* FROM product_color pc
LEFT JOIN product p ON pc.product_id=p.product_id
WHERE p.product_id=1)x on c.id=x.color_id"
$query = $this->db->query($query);
$data = $query->result_array();

I want to pass this query to Eloquent in laravel

I'm trying to make a query with eloquent, I try to get all the users who have one or more ads, taking into account that it is a one to many relationship (users to ads).
This query in general does what I want, but I do not know if it is well done and also how to pass it to Eloquent through the User model.
SELECT users.id, COUNT( anuncio.id ) AS 'total' FROM users
INNER JOIN anuncio ON users.id = anuncio.usuario_id WHERE
(SELECT COUNT( * ) FROM anuncio WHERE anuncio.usuario_id = users.id) >0
GROUP BY users.id ORDER BY total DESC
I have tried several ways that only return Builder to me.
For example:
$listas = new User;
$listas = $listas->join('anuncio','users.id','=','anuncio.usuario_id');
$listas = $listas->select(array('users.*', DB::raw('COUNT(anuncio.id) AS total')));
$listas = $listas->where(function($query) use ($listas){
$query->select(DB::raw('COUNT(anuncio.usuario_id)'))
->where('anuncio.usuario_id','=','users.id')
->groupBy('anuncio.usuario_id');
},'>','0');
$listas = $listas->orderBy('total','DESC')->paginate(48);
By any suggestion I will be very grateful.
Try with this
$listas = User::join('anuncio','users.id','=', 'anuncio.usuario_id')
->select('users.id',DB::raw("count(anuncio.id) as total"))
->groupby('users.id')
->having('total', '>', '0')
->orderby('total', 'desc')
->get();
Just use left join for this.
$users = DB::table('users')
->leftJoin('anuncio', 'users.id', '=', 'anuncio.usuario_id')
->get();
So Left Join will only select those result which has any match in anuncio table.

Interleaving the rows of two different SQL tables, group by one row

My Sql query is like this
$view = mysql_query ("SELECT domain,count(distinct session_id) as
views FROM `statistik` left join statistik_strippeddomains on
statistik_strippeddomains.id = statistik.strippeddomain WHERE
`angebote_id` = '".(int)$_GET['id']."' and strippeddomain!=1
group by domain having count (distinct session_id) >
".(int)($film_daten['angebote_views']/100)." order
count(distinct session_id$vladd) desc limit 25");
How can I write its Codeigniter Model I appreciate any Help
try this
$this->db->select('statistik.domain,statistik.count(DISTINCT(session_id)) as views');
$this->db->from('statistik');
$this->db->join('statistik_strippeddomains', 'statistik_strippeddomains.id = statistik.strippeddomain', 'left');
$this->db->where('angebote_id',$_GET['id']);
$this->db->where('strippeddomain !=',1);
$this->db->group_by('domain');
$this->db->having('count > '.$film_daten['angebote_views']/100, NULL, FALSE);
$this->db->order_by('count','desc');
$this->db->limit('25');
$query = $this->db->get();
Comment me If you have any query.

Getting results form a query to insert in other using active records

I'm needeing to get all the child categories from the given to use in a where_in with active records of codeigniter.
The problem is that the second query get mixed with the main one breaking it completely.
Main Query
$this->db->select('artworks.*, users.id as owner, users.name as user_name');
$this->db->from('artworks');
$this->db->join('users', 'users.id = artworks.user_id');
$category = $this->get_child_categories($this->get_categories(), $matches[1]);
$this->db->where_in('artworks.category', $this->category['child']);
$this->db->group_by('artworks.id');
$query = $this->db->get();
return $query->result_array();
Second Query "get_categories()"
$this->db->select('*');
$this->db->order_by('parent', 'asc');
$this->db->order_by('name', 'asc');
$query = $this->db->get('categories');
return $query->result_array();
get_child_categories
function get_child_categories($categories, $parent){
foreach($categories as $category){
if($category['parent'] == $parent){
array_push($this->category['childs'], $category['id']);
$this->get_child_categories($categories, $category['id']);
}
}
}
But i'm getting this error where clearly displays that the second query is quetting inside the main one.
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* FROM (`artworks`, `categories`) JOIN `users` ON `users`.`id` = `artworks`.`use' at line 1
SELECT `artworks`.*, `users`.`id` as user_id, `users`.`name` as user_name, * FROM (`artworks`, `categories`) JOIN `users` ON `users`.`id` = `artworks`.`user_id` WHERE `artworks`.`rating` IN ('g', 'm', 'a') ORDER BY `artworks`.`id` desc, `parent` asc, `name` asc
Filename: D:\Server\htdocs\gallery\system\database\DB_driver.php
Line Number: 330
I personally think this is an error in CodeIgniter's Active Record approach, if it's supposed to follow the Active Record pattern at all. It should totally enforce either one of these:
queries contained in a single data context
queries specified in a atomic instruction
As neither of these is happening, at the moment you're unwillingly mixing two queries with a structure that CodeIgniter does not support, thus creating that invalid query.
For a simple solution, I would suggest for you to invert the order of the instructions so that the queries are executed separately.
$category = $this->get_child_categories($this->get_categories(), $matches[1]);
# the first query gets executed here, your data context is cleaned up
$this->db->select('artworks.*, users.id as owner, users.name as user_name');
$this->db->from('artworks');
$this->db->join('users', 'users.id = artworks.user_id');
$this->db->where_in('artworks.category', $this->category['child']);
$this->db->group_by('artworks.id');
$query = $this->db->get();
# your second query gets executed here
return $query->result_array();

Resources