PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, March 8, 2022

[FIXED] How can I convert native PHP7 into query eloquent Laravel?

 March 08, 2022     eloquent, laravel, sql-server-2012     No comments   

Issue

I'm migrating from php 7 to laravel and am having trouble completing the query. how to solve data query like the example below

$year = date('Y'); $month = date('m');

select id, tglupload, 
substring(CONVERT(varchar,tglupload,106),4,2) date, 
COUNT(1) as Totalemployeall
from [MS_SK] 
where substring(CONVERT(varchar,tglupload,106),4,2) = $month
and substring(CONVERT(varchar,tglupload,106),7,4) = $year
AND (status_allow <> 'NOTALLOW' OR status_allow is null)
GROUP BY rollup(id, tglupload)
order by id ASC

Solution

Unfortunately you have to use a raw query for that. But you can make your query nicer using the Laravel's scope function.

For example in your model (the model related with the table [MS_SK]) you can add the following 2 scope functions:

class YourModel extends Model {

    public function scopeFiltrateTglUpload($query, int $month=null, int $year=null)
    {
        $year = $year ?? date('Y');
        $month = $month ?? date('m');

        return $query->where(\DB::raw("substring(CONVERT(varchar,tglupload,106),4,2)", "=", $month))
            ->where(\DB::raw("substring(CONVERT(varchar,tglupload,106),7,4)", "=", $year));
    }

    public function scopeTheStatusIsNullOrNotAllowed($query)
    {
        return $query->where(function($subQuery) {
            $subQuery->where('status_allow', '<>', 'NOTALLOW')
                ->orWhereNull('status_allow');
        });
    }

}

Then you can use them as per below:

$result = YourModel::selectRaw('
        `id`, `tglupload`, 
        substring(CONVERT(varchar,tglupload,106),4,2) `date`, 
        COUNT(1) as `Totalemployeall`
    ')
    ->filtrateTglUpload()
    ->theStatusIsNullOrNotAllowed()
    ->groupBy(\Db::raw('rollup(id, tglupload)'))
    ->orderBy('id')
    ->get();

Please note that this is just an example to give you an idea. Then you should make it work :) Please tell me in the comment if you need any help.



Answered By - Dan
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing