How to write union query in Laravel? - php

I'm using laravel 5.0 and I have mysql query:
SELECT surat_masuk.id_surat,
surat_masuk.nomor_surat
FROM surat_masuk
WHERE ! EXISTS (SELECT *
FROM file_replace
WHERE id_surat_lama = surat_masuk.id_surat)
AND surat_masuk.id_jenis_surat = '6'
AND surat_masuk.deleted = '0'
UNION
SELECT id_surat_lama
FROM file_replace
WHERE id_surat_baru = '38'
And I write that in my laravel code into:
$nomor_surat1 = DB::table('surat_masuk')->select('id_surat', 'nomor_surat')
->where('id_jenis_surat', '=', $id_jenis_surat)
->where(function ($query) {
$query->where('masa_berlaku_to', '>=', date('Y-m-d'))
->orwhere('masa_berlaku_to', '=', '0000-00-00');
})
->whereExists(function ($query) {
$query
->from('file_replace')
->where('id_surat_lama', '==', 'surat_masuk.id_surat');
})
->where('deleted', '=', '0');
$nomor_surat = DB::table('file_replace')->join('surat_masuk', 'file_replace.id_surat_lama', '=', 'surat_masuk.id_surat')
->select('id_surat_lama', 'nomor_surat')
->where('id_surat_baru', '=', $id_surat_baru)
->union($nomor_surat1)->get();
But I've got nothing showed. Do you know where is the mistakes?

Well, I finally using raw query..
$results = DB::select( DB::raw("SELECT * FROM some_table WHERE some_col = '$someVariable'") );

Please see the answer, that might help you..
SELECT surat_masuk.id_surat,
surat_masuk.nomor_surat
FROM surat_masuk
WHERE ! EXISTS (SELECT *
FROM file_replace
WHERE id_surat_lama = surat_masuk.id_surat)
AND surat_masuk.id_jenis_surat = '6'
AND surat_masuk.deleted = '0'
UNION
SELECT id_surat_lama
FROM file_replace
WHERE id_surat_baru = '38'
//converted to laravel elequent query.
$first_sql=DB::table('surat_masuk as sm1')
->whereNotExists(function($query) {
$query->from('file_replace as fr1')
->where('fr1.id_surat_lama','sm1.id_surat');
})->where('sm1.id_jenis_surat',6)
->where('sm1.deleted',0)
->select('sm1.id_surat', 'sm1.nomor_surat' );
//will return an elequent object, append '->get()' to see the output seperately
$actual_result=DB::table('file_replace as fr2')
->where('fr2.id_surat_baru',38)
->select('fr2.id_surat_lama')
->union($first_sql)
->get();
//will return an array of result set

Related

Select where not in with select

Im trying to do this SELECT IN SQL SERVER
SELECT cast(datediff(DAY, min([fbh].FBH_DATA_INICIAL), CASE
WHEN max([fbh].FBH_DATA_Final) = '9999-12-31' THEN cast(getdate() AS date)
ELSE max([fbh].FBH_DATA_Final)
END)AS FLOAT) / CAST(365 AS FLOAT) AS duration
FROM [funcionario] AS [f]
INNER JOIN [funcionario_banda_historico] AS [fbh] ON [f].[FUN_ID] = [fbh].[FUN_ID]
AND [f].[FUN_BANDA] = [fbh].[FUN_BANDA]
WHERE NOT EXISTS
(SELECT 1
FROM funcionario_banda_historico t1
WHERE t1.fun_id = [fbh].fun_id
AND t1.FBH_DATA_INICIAL > [fbh].FBH_DATA_Final
AND t1.FUN_BANDA <> [fbh].FUN_BANDA )
AND [f].[FUN_ID] = '9999999'
GROUP BY f.fun_id,
[f].[FUN_BANDA]
Im trying to do this select with where not in and select in LARAVEL
protected function getYearsInBand($userId) {
$fbh = DB::table('funcionario as f')
->join('funcionario_banda_historico as fbh', function($join) {
$join->on('f.FUN_ID', '=', 'fbh.FUN_ID');
$join->on('f.FUN_BANDA', '=', 'fbh.FUN_BANDA');
})
->selectRaw('cast(datediff(day,min([fbh].FBH_DATA_INICIAL),case when max([fbh].FBH_DATA_Final) = "9999-12-31" then cast(getdate() as date) else max([fbh].FBH_DATA_Final) end)AS FLOAT)/CAST(365 AS FLOAT) AS duration')
->where('f.FUN_ID', $userId)
->whereNotIn('1', function($q) {
$q->select('*')
->from('funcionario_banda_historico as t1')
->where('t1.fun_id = [fbh].fun_id')
->where('t1.FBH_DATA_INICIAL > [fbh].FBH_DATA_Final')
->where('t1.FUN_BANDA <> [fbh].FUN_BANDA')
->get();
})
->groupBy('f.FUN_ID', 'f.FUN_BANDA')
->first();
if (!$fbh) {
\Log::debug('funcionario_banda_historico not found'); // Grava no log
return 0;
}
return $fbh->duration;
}
and i had the error Invalid column name 'fun_id = [fbh]'
can you help me?
I think it's not correct syntax for "where" clause in Laravel. Instead you should do:
->whereRaw('t1.FUN_ID = fbh.FUN_ID')
->whereRaw('t1.FBH_DATA_INICIAL > fbh.FBH_DATA_Final')
->whereRaw('t1.FUN_BANDA <> fbh.FUN_BANDA')
OR:
->where('t1.FUN_ID', 'fbh.FUN_ID')
->where('t1.FBH_DATA_INICIAL', '>', 'fbh.FBH_DATA_Final')
->where('t1.FUN_BANDA', '<>', 'fbh.FUN_BANDA')
Notice that I also change "fun_id" to uppercase like everywhere in your code. I don't know if "[fbh]" is correct in Laravel, try to type just "fbh". For raw example you may also need to add Database prefix this way - "DB::getTablePrefix()"

How to use where not between in Laravel 5.5?

I am try
ing to get something like this
select * from `users`
inner join `settings`
on `users`.`id` = `settings`.`user_id`
and NOW() NOT BETWEEN quit_hour_start AND quit_hour_end
where `notification_key` != ''
and `device_type` = 'Android'
in eloquent. Does anyone try and get success to build this query in eloquent.
I know I can use \DB::select(DB::raw()); and get my result. But I want to use ie with Laravel eloquent method.
====== update comment for tried queries========
$androidUser = User::join('settings', function ($join) {
$join->on('users.id', '=', 'settings.user_id')
->where(DB::raw("'$currentTime' NOT BETWEEN quit_hour_start AND quit_hour_end"));
})
->where('notification_key', '!=', '')
->where('device_type' ,'=', 'Android')
->get();
$users = DB::table('users')
->whereNotBetween('votes', [1, 100]) // For one column
->whereRaw("? NOT BETWEEN quit_hour_start AND quit_hour_end", [$currentTime]) // Use whereRaw for two columns
->get();
https://laravel.com/docs/5.5/queries, or you can rewrite as to wheres

How to use multiple OR,AND condition in Laravel queries

I need help for query in laravel
My Custom Query: (Return Correct Result)
Select * FROM events WHERE status = 0 AND (type="public" or type = "private")
how to write this query in Laravel.
Event::where('status' , 0)->where("type" , "private")->orWhere('type' , "public")->get();
But it's returning all public events that status is not 0 as well.
I am using Laravel 5.4
Pass closure into the where():
Event::where('status' , 0)
->where(function($q) {
$q->where('type', 'private')
->orWhere('type', 'public');
})
->get();
https://laravel.com/docs/5.4/queries#parameter-grouping
In your case you can just rewrite the query...
select * FROM `events` WHERE `status` = 0 AND `type` IN ("public", "private");
And with Eloquent:
$events = Event::where('status', 0)
->whereIn('type', ['public', 'private'])
->get();
When you want to have a grouped OR/AND, use a closure:
$events = Event::where('status', 0)
->where(function($query) {
$query->where('type', 'public')
->orWhere('type', 'private');
})->get();
Use this
$event = Event::where('status' , 0);
$event = $event->where("type" , "private")->orWhere('type' , "public")->get();
or this
Event::where('status' , 0)
->where(function($result) {
$result->where("type" , "private")
->orWhere('type' , "public");
})
->get();
Try this. It works for me.
$rand_word=Session::get('rand_word');
$questions =DB::table('questions')
->where('word_id',$rand_word)
->where('lesson_id',$lesson_id)
->whereIn('type', ['sel_voice', 'listening'])
->get();
$filter = [];
$filter[] = "type="public" or type = "private"";
$filter[] = "status = 0";
$event = Event::whereRaw(implode(' AND ',$filter))->get();
You can store all condition in filter array and then apply to query

Query from two tables laravel with multiple conditions

I'm trying to write this query in Laravel query
SELECT
table1.*, table2.*
FROM
table1
LEFT JOIN
table2
ON
(table1.id = table2.id AND (table2.field = '' OR table2.field >= '0'))
WHERE
table.id = id
I have problem with how to add inner part AND ( ... ) to the query? Here is what I have so far
$query = Table::select(
DB::Raw('table1.*, table2.*'))
->leftJoin('table2', function($join) {
$join->on('table1.id', '=', 'table2.id')
->where('table2.field', '=', '')
->orwhere('table2.field', '=', '50');
})->where('table1.id', BaseController::getCurrentUser()->id)
->get();
I miss where and how to add AND ...
Do you need to have the AND part as part of ON? If you move it to the WHERE part of your query you could use something like:
$query = Table::select('table1.*', 'table2.*')
->leftJoin('table2', 'table1.id', '=', 'table2.id')
->where('table1.id', BaseController::getCurrentUser()->id)
->where(function ($query){
$query->where('table2.field', '')
->orWhere('table2.field', 50)
});
The result should be the same as from your original query.

Translate raw complex SQL query into Eloquent

Can anyone help me translate this into Eloquent?
select * from resources
left join links
on links.resource_id = resources.id
and (links.ud_id IS NULL OR links.ud_id = '7')
where resources.user_id = '1'
and resources.subject_id = '4'
Thank you in advance
This should do the trick:
DB::table('resources')
->leftJoin('links', function($join) {
$join->on('links.resource_id', '=', 'resources.id');
$join->where(function($query) {
$query->whereNull('links.ud_id');
$query->orWhere('links.ud_id', '=', 7);
});
})
->where('user_id', 1)
->where('subject_id', 4)
->get();

Categories