I want to get posts with total amount of comments created before 2022-05-12 23:59:59. I also have attached timezone filter. I tried the following:
Route::get('/', function () {
$base = Post::withCount([
'comment' => function ($query) {
$query->select(
'id',
'post_id',
DB::raw('convert_tz(created_at, "UTC", "US/Eastern") as created_at_tz')
)->having('created_at_tz', '<=', '2022-05-12 23:59:59')->count();
},
]);
return $base->get();
});
I get error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'posts.id' in 'where clause'
select
count(*) as aggregate
from
(
select
convert_tz(created_at, "UTC", "US/Eastern") as created_at_tz
from
`comments`
where
`posts`.`id` = `comments`.`post_id`
having
`created_at_tz` <= 2022 -05 -12 23: 59: 59
) as `temp_table`
What am I doing wrong?
...
->withCount([
'comment' => function ($query) {
$query->whereRaw('convert_tz(created_at, "UTC", "US/Eastern") <= '2022-05-12 23:59:59'));
}])
...
try this and update me with response
I believe that count at the end is not necessary
Related
I started the query like this:
$students = StudRegProfile::with(['my_campus','work_experience' => function($query) {
$query->selectRaw('*, datediff(dateend, datestart) / 360 as years_of_experience');
}]);
Update:
My query is now like this:
$students = StudRegProfile::with(['my_campus','work_experience'])
->withCount([
'work_experience as years_of_experience' => function($query) {
$query->select(\DB::raw('SUM(datediff(dateend, datestart) / 360)'));
}
]);
Now I have years_of_experience as column in work_experience relationship. My output looks like this:
[
id => 1,
work_experience => [
id => 1,
years_of_experience => 2.4417,
]
]
But when I filter it like this:
$students->whereHas('work_experience', function($query) {
$query->whereRaw('years_of_experience >= 2');
});
It can't find my years_of_experience column.
Query Log:
Update:
My StudRegProfile hasMany work_experience. My work experience has datestart and endstart. I want to get the total difference in datestart and endstart so I can filter it as and input in my form
How can I pass the value of lead_id to my attendance table?
Here is the code from my controller
$scores = Score::with('lead','subject')->get()->groupBy('lead_id');
I want to pass $scores here:
$atnds = DB::table('attendances')
->select(DB::raw('count(*) as total, status'))
->where('status', '=', 'P')
->whereBetween('days', [$from,$to])
->groupBy('status')
**->where('lead_id','=',$scores)**
->get();
Both table Score and Attendance has lead_id is it possible to connect them? i want to perform total base on the lead_id from score table is equal to attendance table. with my code i'm getting this empty array
try this:
$scores = Score::with('lead','subject')->get();
$atnds = DB::table('attendances')
->select(DB::raw('count(*) as total, status'))
->where('status', '=', 'P')
->whereBetween('days', [$from,$to])
->groupBy('status')
->whereIn('lead_id', array_column($scores->toArray(), 'lead_id'))
->get();
where condition in eloquent expects a string/integer value to be pased and not a collection as you are trying to pass it.
After you get the results from this query:
they should be grouped by keys like:
$scores = Score::with('lead','subject')->get()->groupBy('lead_id');
Collection{
1 => Collection{somedata},
2 => Collection{somedata},
}
So i pressume you need only the keys from this collection:
$atnds = DB::table('attendances')
->select(DB::raw('count(*) as total, status'))
->where('status', '=', 'P')
->whereBetween('days', [$from,$to])
->groupBy('status')
->whereIn('lead_id',$scores->pluck('lead_id')->toArray())
->get();
this is the result of DD$scores
"id" => 62
"subject_id" => 4
"lead_id" => 5
"uuid" => "36c850d0-9ec9-11e8-85e1-cdb65cbc1965"
"created_at" => "2018-08-13 07:19:27"
"updated_at" => "2018-08-13 07:19:27"
]
the total is not there
I am having some trouble in Laravel using the query builder to select users based on two where clauses.
The first where clause would contain multiple where statements to select a user based on some conditions. If this fails in the OR part I would like to check simply if the user ID is in the array.
Would be grateful for some advice on how I could achieve this.
Thanks.
$rs = DB::table('tblUser')
->select('name')
->where(function($q) {
$q->where(function($q){
$q->where('fid', '=', $this->argument('fid'))
->where('type', '<', 10)
})
->orWhereIn('id', $userIdSArray);
})
->get();
$userIdSArray = [ '2', '4', '5' ];
$rs = DB::table( 'Users' )
->select( 'name' )
->where( function ( $q ) use ( $userIdSArray ) {
$q->where( function ( $q ) {
$q->where( 'fid', '=', $this->argument( 'fid' ) )
->where( 'type', '<', 10 );
})
->orWhereIn( 'id', $userIdSArray );
})
->get();
I think you need to pass $userIdSArray in Query builder . And You also forgot (;) after [->where( 'type', '<', 10 )]
I have this database structure
table tools table details
----------- -------------
id * id *
name balance_shoot
tool_id
I need to get count of tools that has balance_shoot in tool_details that is lesser than or equal zero (danger) and more than a zero (save). something like :
[
danger_count => 0,
save_count => 5
];
I already achieve this:
public function index(Request $request){
$trans_date = date('Y-m-d');
$tools = Tool::select('id')
->whereHas(
'details' , function ($query) use ($trans_date){
$query->where('trans_date', $trans_date );
}
)
/*->with([
'details' => function ($query) use ($trans_date){
$query->where('trans_date', $trans_date );
}
])*/
->withCount([
'details as danger' => function ($query) use ($trans_date){
$query->where('trans_date', $trans_date )->where('balance_shoot', '<=', 0 );
},
'details as save' => function ($query) use ($trans_date){
$query->where('trans_date', $trans_date )
->where('balance_shoot', '>', 0 );
},
]);
return $tools->get();
}
And it's return this :
"tools": [
{
"id": 101,
"danger_count": "0",
"save_count": "1"
},
{
"id": 102,
"danger_count": "0",
"save_count": "1"
}
];
How can I get that data structure but in one single result return ??
SQL Query
select count(*) total, sum(case when balance_shoot < '0' then 1 else 0 end) danger, sum(case when balance_shoot > '0' then 1 else 0 end) safe from tool_dtl group by tool_id
In Laravel you can try this
<?php
$toolDtl = Detail::select(
array(
DB::raw('COUNT(*) as total'),
DB::raw("SUM(CASE
WHEN balance_shoot < '0' THEN 1 ELSE 0 END) AS danger"),
DB::raw("SUM(CASE
WHEN balance_shoot > '0' THEN 1 ELSE 0 END) AS save")
)
)
->groupBy('tool_id')
->orderBy('id', 'asc')->get();
?>
We can count directly using conditional SUM
Detail::select([
DB::raw('COUNT(*) as total'),
DB::raw("SUM(balance_shoot < '0') AS danger"),
DB::raw("SUM(balance_shoot > '0') AS save")
])
I have to run a MYSQL select query where the query returns all values that have the beginning date 10 days after today. I have tried these two methods none of which seem to work, where do I need to make a change?
$fix_d_table = TableRegistry::get('fixed_departures');
$f_dates_march = $fix_d_table ->find("all")
->where(['trek_id' => 3])
->andWhere(['month(date_from)' => 03])
->andWhere(['date_from' >= date("Y-m-d",strtotime("+10 days"))])
->order(['date_from'=>'asc'])
->select(['date_from', 'date_to', 'seats_available','id'])
->toArray();
$fix_d_table = TableRegistry::get('fixed_departures');
$f_dates_march = $fix_d_table ->find("all")
->where(['trek_id' => 3])
->andWhere(['month(date_from)' => 03])
->andWhere(['date(date_from)' >= date("Y-m-d",strtotime("+10 days"))])
->order(['date_from'=>'asc'])
->select(['date_from', 'date_to', 'seats_available','id'])
->toArray();
Try below one
$fix_d_table = TableRegistry::get('fixed_departures'); $f_dates_march
= $fix_d_table ->find("all")
->where(['trek_id' => 3])
->andWhere(
function ($exp) {
return $exp->or_([
'date_from <=' => date('Y-m-d', strtotime("+10 days")),
'date_from >=' => date('Y-m-d')
]);
})
->order(['date_from'=>'asc'])
->select(['date_from', 'date_to', 'seats_available','id'])
->toArray();
should be
'date_from >=' => date("Y-m-d",strtotime("+10 days"))
if you can rely on mysql server date you can use NOW() inside your query
->where(function($exp, $q) {
return $exp->gte($q->func()->dateDiff([
'date_from ' => 'identifier',
$q->func()->now() ]), 10);
});
this will give you the following SQL condition
WHERE
(
DATEDIFF(date_from , NOW())
) >= 10