I want to do query both result and count with group_by.
$id= 2;
$limit = 10;
$offset = ($id - 1) * $limit;
$this->db->group_by('BE.etiket_id');
$this->db->from('bulten_icerigi_etiketler as BE');
$this->db->join('etiketler as E', 'BE.etiket_id=E.id', 'left');
$this->db->join('bulten_icerigi as BI', 'BE.bulten_id=BI.id', 'left');
$count = $this->db->count_all_results('', false);
$this->db->limit($limit, $offset);
$this->db->order_by('E.adi');
$results = $this->db->get()->result();
However, I have error
Error Number: 1054
Unknown column 'tbl_`E.adi' in 'field list'
Can I use count_all_results() and result() together ?
Thank you.
You can't group by columns which you didn't selected in select.
Try to use E.adi and E.id instead of BE.etiket_id in your group by.
Your query should looks like:
SELECT
COUNT(*) as count,
tbl_E.adi,
tbl_E.id
FROM tbl_bulten_icerigi_etiketler as BE
LEFT JOIN tbl_etiketler as E ON BE.etiket_id=E.id
LEFT JOIN tbl_bulten_icerigi as BI ON BE.bulten_id=BI.id
GROUP BY tbl_E.adi, tbl_E.id // here you need to change
ORDER BY tbl_E.adi
$this->db->group_by(array("E.adi", "E.id"));
Related
I've created MySQL query for searching results. The query works properly but if I use laravel pagination on this query I get an error
Call to a member function paginate() on array ,
How to solve this with pagination?
$search = \DB::SELECT("SELECT l.*,
r.id AS reservation_id,
r.status AS res_status,
r.start_date,
r.end_date,
Avg(r.rating) AS rating
FROM listings l
LEFT JOIN reservations r ON r.listing_id = l.id
WHERE ( ( Cast('" . $search_date . "' AS date) NOT BETWEEN r.start_date AND r.end_date ) OR r.status = 'Cancel' )
AND l.city_id = $city_id
AND l.persons >= $guests
AND l.listing_type_id = $type
GROUP BY l.id
ORDER BY r.rating DESC
");
DB::select() will return an array. You could probably convert your query to a Query Builder and then use paginate() on it. For example:
$search = DB::table('listings')
->selectRaw('listings.*, reservations.id AS reservation_id, reservations.status AS res_status, reservations.start_date, reservations.end_date, AVG(reservations.rating) as rating')
->leftJoin('reservations', 'reservations.listing_id', 'listings.id')
->whereRaw("(CAST(? AS date) NOT BETWEEN reservations.start_date AND reservations.end_date) or reservations.status = 'Cancel'", [$search_date])
->where('listings.city_id', '=', $city_id)
->where('listings.persons', '>=', $guests)
->where('listings.listing_type_id', '=', $type)
->groupBy('listings.id')
->orderBy('reservations.rating', 'DESC')
->paginate(10);
I know that something similar was here some time ago,but it wasn't the same case and I can't just figure it out on myself.
I need to transform raw SQL query to Eloquent.
This query contains SELECT COUNT in WHERE clause, for simplicity I have this (may has not much sense) query :
SELECT u.column1, u.column2, u.column3, s.column1 FROM users u
LEFT JOIN salary s ON u.id = s.user_id
WHERE
(
SELECT count(cars_id) FROM cars WHERE cars.user_id = u.id
) = 0
AND u.city IN ("London","Paris")
I tried:
$columns = [
'users.column1',
'users.column2',
'users.column3',
'salary.column1'
];
$q = User::select($columns)
->leftJoin('salary', 'salary.user_id', '=', 'users.id')
->whereRaw(" (SELECT COUNT(cars_id) FROM cars WHERE cars.user_id = u.id) = 0 ")
->whereRaw("u.city IN ('London','Paris')")
->get();
But it doesn't return same results as raw SQL (SQL had 161 rows and Eloquent 154 rows).
Maybe you know how to transform this kind of query correctly to Eloquent?
Thanks
Based on your query I believe this should do it:
DB::table('users as u')
->select([ 'u.column1', 'u.column2', 'u.column3', 's.column1'])
->leftJoin('salary as s', 'u.id', '=', 's.user_id')
->leftJoin('cars as c', 'c.user_id', '=', 'u.id')
->whereIn('u.city', ['London', 'Paris'])
->havingRaw('count(c.id) = 0')
->get();
Please let me know.
The goal is to sort my campaigns by views in my filtration, which is why i have an analytics table with relations to my campaigns
My campaign model (The DB name is "ads"):
public function views() {
return $this->hasMany('App\Analytic', 'foreign_id', 'id')->where('foreign_type', '=', 'campaign');
}
The controller of my filtration:
$query = Ad::withCount('views')->with('tags');
$query->where("is_active", "=", 1);
$query->where("status", "=", 1);
$query->orderBy('views_count', 'DESC');
$campaigns = $query->get();
Now the reason for not writing it without the $query-> part, is because the query has lots of if statements depending on filtration settings.
The error im getting:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'views_count' in 'order clause' (SQL: select count(*) as aggregate from `ads` where `is_active` = 1 and `status` = 1 and `from_year` >= 7 and `to_year` <= 88 and `price` >= 1000 and `price` <= 64000 order by `views_count` desc)
The error is it tries to fetch a column, but i can't figuere out why.
If i try to access $campaign->views_count in my blade template, it shows the count just fine.
Thank you for your time, i hope someone can tell me what I'm doing wrong here.
The error you're getting is a result of a count() method not a get().
something like this
$query = Ad::withCount('views')->with('tags');
$query->where("is_active", "=", 1);
$query->where("status", "=", 1);
$query->orderBy('views_count', 'DESC');
$campaignCount = $query->count();
wich replaces the complex select part with:
select count(*) as aggregate
if you need the count() and the get(), do it like this:
$query = Ad::withCount('views')->with('tags');
$query->where("is_active", "=", 1);
$query->where("status", "=", 1);
$campaignCount = $query->count();
$query->orderBy('views_count', 'DESC');
$campaigns = $query->get();
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.
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();