How to Query Raw via Eloquent

How can I query raw via Eloquent?

use DB::statement('your raw query here'). Hope this helps.

How do I get the query builder to output its raw SQL query as a string?

To output to the screen the last queries ran you can use this:

\DB::enableQueryLog(); // Enable query log

// Your Eloquent query executed by using get()

dd(\DB::getQueryLog()); // Show results of log

I believe the most recent queries will be at the bottom of the array.

You will have something like that:

array(1) {
[0]=>
array(3) {
["query"]=>
string(21) "select * from "users""
["bindings"]=>
array(0) {
}
["time"]=>
string(4) "0.92"
}
}

(Thanks to Joshua's comment below.)

How to retrieve the data from Eloquent or raw Query in Laravel?

you can use

DB::select("
SELECT cnt, `creationdate`, week, weekname,
DATE_ADD(firstOfMonth,INTERVAL (week-1) WEEK) as 'Week Start',
IF(DATE_ADD(firstOfMonth,INTERVAL ((week-1)*7+6) DAY) > eom,
eom, DATE_ADD(firstOfMonth,INTERVAL ((week-1)*7+6) DAY)) as 'Week End'
FROM (
SELECT COUNT(`firstname`) AS 'cnt', `creationdate`,
FLOOR((DAYOFMONTH(`creationdate`) - 1) / 7 +1) AS week,
CONCAT('Week ',FLOOR((DAYOFMONTH(`creationdate`) - 1) / 7) +1) AS weekname, DATE_ADD(`creationdate`,interval -DAY(`creationdate`)+1 DAY) AS firstOfMonth,
LAST_DAY(`creationdate`) as 'eom'
FROM `UserDetails` WHERE DATE_FORMAT(`creationdate`,'%m/%Y')='06/2017' GROUP BY week ) a
");

if you don't have any parameter to add to the query that comes from the request/other third party (and so there is no SQL injection risk)

How can I write this raw query using Laravel's Eloquent?

I have got answer, I have tried these codes..

\Model\Order::query()
->select('id', 'shipping_email')
->whereRaw("`shipping_email` NOT REGEXP ?", ["^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,63}$"])
->get();

How to convert this raw sql query to laravel eloquent or query builder?

Try in this way.
For more details Check: https://laravel.com/docs/8.x/queries

$query  = DB::table('employees as emp')
->leftjoin('attendance_log as al','al.emp_id','emp.device_emp_id')
->join('departments as dep','dep.id','emp.department_id')
->select('emp.*', 'dep.department_name', 'al.auth_date' , DB::raw("MIN(al.auth_time) AS check_in, MAX(al.auth_time) AS check_out"))
->whereIn('al.emp_id', [1,2,3]) // use your array
->groupBy('emp.device_emp_id', DB::raw('DATE(al.auth_date_time)'));

if($start_date){
$query = $query->where('al.auth_date' , '>=' , $start_date);
}
if($end_date){
$query = $query->where('al.auth_date' , '<=' , $end_date);
}
$data = $query->get();

Please How to convert this raw sql query to laravel eloquent or query builder?

from query i assume Server can belong to many Users and User can have many Servers, and both has many ServerUserCancellation, so you need servers for current user with cancellations existence flag

first define relations that fits your database schema

// Server model
public function cancellations(){
return $this->hasMany(ServerUserCancellation::class);
}

public function users(){
return $this->belongsToMany(User::class);
}

// User model
public function servers(){
return $this->belongsToMany(Server::class);
}

now you can count cancellations and filter servers which has current user according to users relation

$baseFilters = [
'is_active' => true,
'is_installed' => true,
];
$result = Server::where($basicFilters)
->whereNull('deleted_at')
->whereHas('users', function($query){
$query->where('user_id', auth()->id());
})
->withCount(['cancellations as exists' => function($query){
$query->where('user_id', auth()->id();
}])
->select(['id', 'ip', 'name'])
->get();

//result strucure will be looking like this
array(
[
'id': 1,
'ip': '127.0.0.1',
'name': 'server 1 name',
'exists': 0
],
...
)

to make controller cleaner there is mechanism of soft deleting to skip whereNull('deleted_at') for each Server query and scopes to make code easy to read

// Server model
class Server extends Model {
use SoftDeletes;

public function scopeActive($query){
return $query->where('is_active', true);
}

public function scopeInstalled($query){
return $query->where('is_installed', true);
}

// ... other model code
}

and code will look like this

$result = Server::active()
->installed()
->whereHas('users', function($query){
$query->where('user_id', auth()->id());
})
->withCount(['cancellations as exists' => function($query){
$query->where('user_id', auth()->id();
}])
->select(['id', 'ip', 'name'])
->get();


Related Topics



Leave a reply



Submit