MySQL date in between month and year - mysql

How to query date month and year between from_date and to_date?
What I tired:
$posts = my_table::whereYear('from_date', '>=', $year)
->whereMonth('from_date', '>=', $month)
->whereYear('to_date', '<=', $year)
->whereMonth('to_date', '<=', $month)
->get();
Query I want to execute:
SELECT * FROM my_table
WHERE (MONTH(from_date)>=2 AND (Year(from_date)>=2019)
AND (MONTH(to_date)=<4 AND (Year(to_date)=<2019)

I think this is what you might be looking for:
$posts = my_table::whereRaw("(MONTH('from_date') > 2 AND YEAR('from_date') >= 2019)")
->whereRaw("(MONTH('to_date') < 4 AND YEAR('to_date') <= 2019)")
->get();
Here's an example.

You can use the eloquent method too.
$result = my_table::where(function($query){
$query->where(DB::raw('MONTH(from_date)'), '>=' , 2)
->where(DB::raw('Year(from_date)'), '>=' , 2019);
})
->where(function($query){
$query->where(DB::raw('MONTH(to_date)'), '<=' , 4)
->where(DB::raw('YEAR(to_date)'), '<=' , 2019);
})
->get();

you may also do it in this way.
return Post::whereRaw("STR_TO_DATE('from_date', '%M%Y') > STR_TO_DATE('022019', '%M%Y')")
->whereRaw("STR_TO_DATE('from_date', '%M%Y') < STR_TO_DATE('042019', '%M%Y')")
->get();

Related

Laravel subquery in from clause

I need to use subquery in from clause but i can not find such thing in Laravel docs
Laravel version 5.4
$sub = Chat::join("chats as _chats", function ($query) {
$query->on('chats.room_id', "=", "_chats.room_id")
->on('chats.user_type', "<>", "_chats.user_type")
->on('chats.created_at', "=", DB::raw("(SELECT MIN(created_at) FROM chats WHERE created_at > '_chats.created_at')"));
})
->selectRaw('TIMESTAMPDIFF(MINUTE, _chats.created_at, chats.created_at) as res')
->where('chats.user_type', 'pharmacy_consultant')
->where('chats.user_id', 26)
->toSql();
dd(
DB::connection('mysql2')
->table(DB::raw("({$sub}) as sub"))
->select('res')
->get()
);
(2/2) QueryException SQLSTATE[HY000]: General error: 2031
(SQL: select `res` from (select TIMESTAMPDIFF(MINUTE, _chats.created_at, chats.created_at) as res
from `chats` inner join `chats` as `_chats` on `chats`.`room_id` = `_chats`.`room_id` and `chats`.`user_type` <> `_chats`.`user_type` and `chats`.`created_at` =
(SELECT MIN(created_at) FROM chats WHERE created_at > _chats.created_at) where `chats`.`user_type` = ? and `chats`.`user_id` = ?) as sub)
Try passing the builder instance instead of the raw query.
// $sub = Query Builder instance
$sub = Chat::join("chats as _chats", function ($query) {
$query->on('chats.room_id', "=", "_chats.room_id")
->on('chats.user_type', "<>", "_chats.user_type")
->on('chats.created_at', "=", DB::raw("(SELECT MIN(created_at) FROM chats WHERE created_at > '_chats.created_at')"));
})
->selectRaw('TIMESTAMPDIFF(MINUTE, _chats.created_at, chats.created_at) as res')
->where('chats.user_type', 'pharmacy_consultant')
->where('chats.user_id', 26);
// ->toSql();
DB::connection('mysql2')
->table($sub, "sub")
->select('res')
->get()
Since you're not doing anything else than a select in your final query, why not just do that in the first query instead?
$results = Chat::join("chats as _chats", function ($query) {
$query->on('chats.room_id', "=", "_chats.room_id")
->on('chats.user_type', "<>", "_chats.user_type")
->on('chats.created_at', "=", DB::raw("(SELECT MIN(created_at) FROM chats WHERE created_at > '_chats.created_at')"));
})
->selectRaw('TIMESTAMPDIFF(MINUTE, _chats.created_at, chats.created_at) as res')
->where('chats.user_type', 'pharmacy_consultant')
->where('chats.user_id', 26)
->select('res')
->get();
Make it fit to your needs:
...
->addSelect([res' => ChartModel::select('//whatever')
->whereColumn('//sub-query column', 'parent-table.field')
->whereColumn('//and whatever')
->latest()
->take(1)
)]
...

Translate a MySql query in a Laravel query builder

SELECT apartment_id, COUNT(created_at) AS n_view,
DATE_FORMAT(created_at, '%Y-%m-%d') as day_view
FROM views
WHERE apartment_id=36 GROUP BY day_view
ORDER BY COUNT(created_at) DESC
how can I Translate this MySql query in a Laravel query builder ?
Check Laravel docs on query builder and see the examples, you can easily convert your SQL to query builder:
use Illuminate\Support\Facades\DB;
DB::table('views')
->selectRaw("apartment_id, COUNT(created_at) AS n_view, DATE_FORMAT(created_at, '%Y-%m-%d') as day_view")
->where('apartment_id', '=', 36)
->groupBy('day_view')
->orderByRaw('COUNT(created_at) DESC')
->get();
You can do like that use App\Views; use DB;
Views::select('apartment_id', DB::raw("COUNT(created_at) as n_view") ,DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d') as day_view"))->where('apartment_id' ,36)->orderBy('n_view', 'desc')->get();
$data = $this->views;
$data = $data->select(
"apartment_id",
DB::raw("COUNT(created_at) AS n_view"),
DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d') as day_view")
);
$data = $data->where("apartment_id", 36);
$data = $data->groupBy("day_view");
$data = $data->orderBy("created_at", "desc");
$data = $data->get();
DB::table('views')
->selectRaw("apartment_id, COUNT(created_at) AS n_view, DATE_FORMAT(created_at, '%Y-%m-%d') as day_view")
->where("apartment_id", "=", "36")
->groupBy('day_view')
->orderBy(n_view, "DESC")
->get();

Laravel MySQL groupby created_at with date format without time

I have a table column named created_at type datetime.
and I want to use groupby for created_at with date only and without time.
Here's my existing code :
$data = BloodPressureHistory::where('user_id', $id)
->groupBy('created_at')
->orderBy('created_at', 'DESC')
->paginate(7);
Use groupBy(DB::raw()) and DATE_FORMAT like this:
$data = BloodPressureHistory::where('user_id', $id)
->groupBy(DB::raw('DATE_FORMAT(created_at,"%Y-%m-%d")'))
->orderBy('created_at', 'DESC')
->paginate(7);
$data = BloodPressureHistory::where('user_id', $id)
->groupBy(function ($item){
return \Illuminate\Support\Carbon::parse($item->created_at)->format('Y-m-d');
})
->orderBy('created_at', 'DESC')
->paginate(7);

Laravel DB query with count

I have a query where i need to use count and have a normal query.
Normal
select sum(total) as Total,AffID,user_id from Affiliates
group by AffID order by user_id ASC
And Then
foreach($result_array as $row)
{
echo $row['total']."<br/>";
echo $row['AffID']."<br/>";
echo $row['user_id ']."<br/>";
}
In Laravel i have tried
$affdata = DB::select('Affiliates')
->whereRaw('CompletedDate >= curdate()')
->groupBy('AffID')
->orderBy('user_id', 'ASC')
->sum('total');
->get();
foreach($affdata as $row)
{
echo $row->AffID ."<br>";
echo $row->total ."<br>";
}
But it seems to throw out an error. As i need to echo out the AFFID along with calculating the Total
Update your query to this.
$affdata = DB::table('Affiliates')->select(DB::raw('sum(total) as total'), 'AffID', 'user_id'))
->whereRaw('CompletedDate >= curdate()')
->groupBy('AffID')
->orderBy('user_id', 'ASC')
->sum('total');
->get();
This is the correct query
$affdata = DB::table('Affiliates')->select(DB::raw('sum(total) as total'), 'AffID', 'user_id')
->whereRaw('CompletedDate >= curdate()')
->groupBy('AffID')
->orderBy('user_id', 'ASC')
->get();

CURDATE() with laravel 5

I'm new to laravel and i am wanting to use multiple where clauses and use curdate().
This is an example :
$data = DB::table('toutcome')->where('date', '>=', curdate())->where('Status', '=', 'A')->count('AppID');
return view('home', compact('data'));
It's not working at all.
So along with the answers in the comments:
public function index()
{
// First query with DB::raw() variant
$data = DB::table('toutcome')
->where('date', '>=', DB::raw('curdate()'))
->where('Status', '=', 'A')
->count('AppID');
// Second query with Carbon variant
$data2 = DB::table('toutcome')
->where('date', '>=', Carbon::now())
->where('Status', '=', 'A')
->count('AppID');
// Third query with '#Sunny' whereRaw variant
$data3 = DB::table('toutcome')
->whereRaw('date >= curdate()')
->where('Status', '=', 'A')
->count('AppID');
return view('home', compact('data','data2','data3'));
}
I'm not a big fan of compact() personally so I would write:
return view('home', ['data'=>&$data,'data2'=>&$data2,'data3'=>&$data3])
although personally (if you want to read on taking it further) read up on ViewComposers:
https://laravel.com/docs/master/views#view-composers
Change
where('date', '>=', curdate())
to
whereRaw('date >= curdate()')