cake php distinct date_format - distinct

Please I need some help with cakephp3 mysql distinct.
My desire result in SQL:
select distinct(date_format(torokuDate,'%Y')) as year
from kani_tbl
where torokuDate >= '2000-01-01'
order by torokuDate ASC
limit 1;
But I get the wrong result:
SELECT (date_format((torokuDate), '%Y')) AS `year`
FROM kani_tbl
WHERE torokuDate > :c0
GROUP BY torokuDate
ORDER BY torokuDate ASC
LIMIT 1
My model src:
$query = $this->find();
$time = $query->func()->date_format([
'torokuDate' => 'identifier',
"'%Y'" => 'literal'
]);
$yearList = $query->select(['year' => $time])
->distinct('torokuDate')
->from('kani_tbl ')
->order(['torokuDate' => 'ASC'])
->where(['torokuDate >' => '2000-01-01'])
->limit(1);
// ->hydrate(false)
// ->toArray();
var_dump($yearList);
Please help me to add distinct field in the MySQL command.

As your expected query, you need to distinct result of date_format(torokuDate, '%Y'), not the 'torokuDate' field. So your code should be like this:
$yearList = $query->select(['year' => $time])
->distinct()
->from('kani_tbl ')
->order(['torokuDate' => 'ASC'])
->where(['torokuDate >' => '2000-01-01'])
->limit(1);
How to use distinct method: https://api.cakephp.org/3.4/class-Cake.Database.Query.html#_distinct

Related

I have no data with joined ad_categories table

In laravel 8 I make request with condition on joined ad_categories table :
$adsCategories = [1,2,3,4,6,7,8];
$data = Ad
::whereDate('expire_date', '>=', $date_start)
->whereDate('expire_date', '<', $date_end)
->orderBy($order_by, $order_direction)
->with('adCategories')
->with('creator')
->withCount('adLocations')
->leftJoin('ad_categories', 'ad_categories.ad_id', '=', 'ads.id')
->whereIn('ad_categories.category_id', $adsCategories)
->get();
and tracing sql :
SELECT `ads`.*, ( SELECT count(*)
FROM `ad_locations`
WHERE `ads`.`id` = `ad_locations`.`ad_id`) AS `ad_locations_count`
FROM `ads`
LEFT JOIN `ad_categories` on `ad_categories`.`ad_id` = `ads`.`id`
WHERE date(`expire_date`) >= '2021-04-01' AND date(`expire_date`) < '2021-05-01' AND `ad_categories`.`category_id` in ('1', '2', '3', '4', '6', '7', '8')
ORDER BY `expire_date` asc, `price` desc
I got no rows returned, but in database I see ralated rows :
Manually removing rows with ad_categories.category_id` :
SELECT `ads`.*, ( SELECT count(*)
FROM `ad_locations`
WHERE `ads`.`id` = `ad_locations`.`ad_id`) AS `ad_locations_count`
FROM `ads`
LEFT JOIN `ad_categories` on `ad_categories`.`ad_id` = `ads`.`id`
WHERE date(`expire_date`) >= '2021-04-01' AND date(`expire_date`) < '2021-05-01'
ORDER BY `expire_date` asc, `price` desc
I got all data I need.
What is wrong ?
Thanks!
use select...
$data = Ad
::whereDate('expire_date', '>=', $date_start)
->whereDate('expire_date', '<', $date_end)
->orderBy($order_by, $order_direction)
->with('adCategories')
->with('creator')
->withCount('adLocations')
->leftJoin('ad_categories', 'ad_categories.ad_id', '=', 'ads.id')
->whereIn('ad_categories.category_id', $adsCategories)
->select('ads.*', 'ad_categories.*') // <- add this line of code
->get();

Codeigniter 3 - Query Builder 'join' Method '!=' operator is not giving expected output

Not a Duplicate Question!!!
I am using CodeIgniter 3 - Query Builder Class with MySQLi.
Tables in DB:
'category_level_1' Table:
'category_level_2' Table:
Query in model.php:
$query = $this->db
->select('category_level_1.id, category_level_1.category')
->from('category_level_1')
->join('category_level_2', 'category_level_2.cat_lvl1_id != category_level_1.id', 'inner')
->group_by('category_level_1.id')
->get();
Output :
Inner-Join not working.
Expected Output :
Only need to output records in 'category_level_1' Table which are not related with 'category_level_2' Table.
Issue:
As showed above, output values are not as expected according to '!=' operator is not working with 'inner' join.
Hope this will help you :
$sql = "SELECT id, category
FROM category_level_1
WHERE id NOT IN (SELECT DISTINCT cat_lvl1_id FROM category_level_2)";
$query = $this->db->query($sql);
print_r($query->result());
Output :
Array
(
[0] => stdClass Object
(
[id] => 93
[category] => dummy
)
)
I suggest you try using a left orright join and a where clause. Give the following a go:
$query = $this->db
->select('category_level_1.id, category_level_1.category')
->from('category_level_1')
->join('category_level_2', 'category_level_2.cat_lvl1_id = category_level_1.id', 'left')
->where('category_level_2.cat_lvl1_id IS NULL')
->group_by('category_level_1.id')
->get();
$query = $this->db ->select('category_level_1.id, category_level_1.category') ->from('category_level_1') ->join('category_level_2', 'category_level_2.cat_lvl1_id <> category_level_1.id', 'inner') ->group_by('category_level_1.id') ->get();

Where clause not enforced

I use laravel eloquent outside laravel.
I have a query that is supposed to get only posts that are featured (featured field = 1) and of any of the 3 types (blog, forum and page).
$latestFeaturedPosts = $db->table( 'posts' )
->where( 'featured', '=', 1 )
->orWhere( 'post_type', '=', 'blog' )
->orWhere( 'post_type', '=', 'forum' )
->orWhere( 'post_type', '=', 'page' )
->limit( 15 )
->orderBy( 'created_at', 'desc' )
->get()->toArray();
I expected this query to return what I wanted, but it does return also posts where featuredcolumn is not 1.
Why ? How should I modify this syntax to enforce this ?
I do not now this language, but will give you a starting point to look into.
Your query will be expanded to:
SELECT * FROM posts where featured = 1 OR post_type = 'blog' OR post_type = 'forum' OR post_type = 'page' LIMIT 15 ORDER BY created_at DESC;
In this query, any row that matches any one of the 4 criteria will be returned.
For you to get the results you expect, your query needs to be evaluated to:
SELECT * FROM posts where featured = 1 AND ( post_type = 'blog' OR post_type = 'forum' OR post_type = 'page' ) LIMIT 15 ORDER BY created_at DESC;
In this example, we will always enforce the featured type, and then can select any 3 types that are also featured.
How to do this in your language, I am not sure.
This will work for you:
$db->table('posts')
->where('featured', 1)
->whereIn('post_type', ['blog', 'forum', 'page'])
->limit(15)
->orderBy('created_at', 'desc')
->get()->toArray();
Your query doesn't work as expected because you're using orWhere() without a closure which would group orWhere() clauses.

Laravel 4: insert with max+1 in laravel

I want to run the following query
INSERT INTO static_pages (`page_name`, `title`, `page_display_order`) SELECT 'test','test', MAX(page_display_order)+1 FROM static_pages;
How to execute this query with laravel eloquent? Is that possible?
Update
Thanks #Joseph Silber
I used this in elaquant as like
$staticpage->page_display_order = DB::raw("($subquery)");
$staticpage->save();
That helped to get the last inserted id.
Use DB::raw() with a subquery:
$subquery = DB::table((new StaticPage)->getTable() . ' as page_alias')
->selectRaw('page_display_order + 1 as pdo')
->orderBy('page_display_order', 'desc')
->take(1)->toSql();
StaticPage::create([
'page_name' => 'test',
'title' => 'test',
'page_display_order' => DB::raw("($subquery)"),
]);

Cannot run raw Query in Laravel 4

I need to get total count to show in my page.
I can run this & loop through & get the total number
DB::table('table1')
->select((DB::raw('MAX(score)')))
->where('status', 1)
->groupBy('user_id')
->get();
But this query would give me the count in just a single query & I don't need run any extra loop to get the total.
SELECT COUNT( * ) FROM (
SELECT MAX( score ) FROM table1
WHERE status =1
GROUP BY user_id
) AS totalCounter
How am I suppose to run this RAW query in Laravel 4?
Try
DB::statement( 'Your Query' );
or
DB::select( 'Your Query' );
As mentioned by other contributors;-
DB::select('SQL QUERY GOES HERE WITH PARAMETERS ?, ?', array('parameter 1', 'parameter 2'));
The code above should permit raw sql.
However,
DB::table('table1')
->select((DB::raw('MAX(score)')))
->where('status','=', 1)
->groupBy('user_id')
->count();
Should achieve the same effect for the task you seek it for, and is more in tune with laravels philosophy.
DB::select(DB::raw("SQL QUERY CODE HERE"))
Both raw and select are require!
Please see for more info:
Laravel 4: how to run a raw SQL?
Try this
DB::select( DB::raw("SELECT * FROM table_Name WHERE col = :somevariable"), array(
'somevariable' => $someVariable,
));

Resources