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)"),
]);
Related
I tried this in laravel, but it's not working. I can't get it to work it's working when I use it straight on PHPMyAdmin
SELECT service,
count(*) as total_count,
sum(if(status ='Successful',1,0)) as successful_count,
sum(if(status ='Failed',1,0)) as failed_count
FROM `wallet_ledgers`
WHERE operator = "-"
AND user_id = 5
group by service
this is the desired output The way the table should look
You can use DB::raw
Link: Laravel-raw-expressions
$result = DB::table('wallet_ledgers')
->select(DB::raw("service, count(*) as total_count, sum(if(status ='Successful',1,0)) as successful_count, sum(if(status ='Failed',1,0)) as failed_count"))
->where([
[ 'operator', '=', '-'],
['user_id', '=', '5'],
])
->groupBy('service')
->get();
My working SQL query is as follows:
SELECT post_id
FROM news_tags
ORDER BY (link_clicks+views) DESC
What I've tried so far in eloquent is like this:
$newsTagSaved = NewsTag::
orderBy(DB::raw("`views` + `link_clicks`"), 'desc')
->paginate(12)
->pluck('post_id');
Newstag table has many columns and views and link_clicks are two of them. Now, I'm trying to retrieve the post_id order by desc of sum of views and link_click.
How can I do it in Laravel eloquent?
Thank you!
Do something like this:
$newsTagSaved = NewsTag::select(DB::raw('views + link_clicks as score'))
->orderBy('score', 'desc')
->get();
dd($newsTagSaved);
This will return just score value. If you want to return other fields, simply add them to select. As an example:
$newsTagSaved = NewsTag::select(
DB::raw('views + link_clicks as score'),
'title',
'created_at'
)
->orderBy('score', 'desc')
->get();
dd($newsTagSaved);
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();
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
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,
));