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
Related
I want to sort multiple columns in Laravel 4 by using the method orderBy() in Laravel Eloquent. The query will be generated using Eloquent like this:
SELECT *
FROM mytable
ORDER BY
coloumn1 DESC, coloumn2 ASC
How can I do this?
Simply invoke orderBy() as many times as you need it. For instance:
User::orderBy('name', 'DESC')
->orderBy('email', 'ASC')
->get();
Produces the following query:
SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC
You can do as #rmobis has specified in his answer, [Adding something more into it]
Using order by twice:
MyTable::orderBy('coloumn1', 'DESC')
->orderBy('coloumn2', 'ASC')
->get();
and the second way to do it is,
Using raw order by:
MyTable::orderByRaw("coloumn1 DESC, coloumn2 ASC");
->get();
Both will produce same query as follow,
SELECT * FROM `my_tables` ORDER BY `coloumn1` DESC, `coloumn2` ASC
As #rmobis specified in comment of first answer you can pass like an array to order by column like this,
$myTable->orders = array(
array('column' => 'coloumn1', 'direction' => 'desc'),
array('column' => 'coloumn2', 'direction' => 'asc')
);
one more way to do it is iterate in loop,
$query = DB::table('my_tables');
foreach ($request->get('order_by_columns') as $column => $direction) {
$query->orderBy($column, $direction);
}
$results = $query->get();
Hope it helps :)
Use order by like this:
return User::orderBy('name', 'DESC')
->orderBy('surname', 'DESC')
->orderBy('email', 'DESC')
...
->get();
Here's another dodge that I came up with for my base repository class where I needed to order by an arbitrary number of columns:
public function findAll(array $where = [], array $with = [], array $orderBy = [], int $limit = 10)
{
$result = $this->model->with($with);
$dataSet = $result->where($where)
// Conditionally use $orderBy if not empty
->when(!empty($orderBy), function ($query) use ($orderBy) {
// Break $orderBy into pairs
$pairs = array_chunk($orderBy, 2);
// Iterate over the pairs
foreach ($pairs as $pair) {
// Use the 'splat' to turn the pair into two arguments
$query->orderBy(...$pair);
}
})
->paginate($limit)
->appends(Input::except('page'));
return $dataSet;
}
Now, you can make your call like this:
$allUsers = $userRepository->findAll([], [], ['name', 'DESC', 'email', 'ASC'], 100);
$this->data['user_posts'] = User_posts::with(['likes', 'comments' => function($query) { $query->orderBy('created_at', 'DESC'); }])->where('status', 1)->orderBy('created_at', 'DESC')->get();
I have orders table which contains status, paymode, pay_status column
I want to get order if paymode is cod then pay_status unconfirmed can get
and
if paymode is payu then pay_status only confirmed can get
Here I tried with whereRaw
$orders = Order::whereHas('products', function (Builder $query) use ($seller) {
$query->where('seller_id', $seller->id);
})
->whereRaw('IF (`paymode` = `payu`, `pay_status` = `confirmed`)')
->paginate(25);
but it's not working
you can try like this also for multiple conditions
$orders = Order::whereHas('products',
function (Builder $query) use ($seller) {
$query->where('seller_id', $seller->id);
})->whereRaw('paymode = ? AND pay_status = ?', ['payu','confirmed'])
->orWhereRaw('paymode = ? AND pay_status = ?', ['cod','unconfimed '])
->paginate(25);
below is my query . i want to get all results If (nic or mobile) and course matches ,
please advice
$conversations = Inquiries::whereRaw("( `course` = $request->input('course'))
AND( `mobile` = $request->input('mobile') OR 'nic', 'LIKE', '%'.$request->input('nic').'%')")
->get();
You need to properly create a query, like this:
$conversations = Inquiries::where('course', '=', $request->input('course'))
->where(function($query) use ($request) {
$query->where('mobile','=', $request->input('mobile'))
->orWhere('nic','LIKE','%'.$request->input('nic').'%');
})
->get();
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
I want to sort multiple columns in Laravel 4 by using the method orderBy() in Laravel Eloquent. The query will be generated using Eloquent like this:
SELECT *
FROM mytable
ORDER BY
coloumn1 DESC, coloumn2 ASC
How can I do this?
Simply invoke orderBy() as many times as you need it. For instance:
User::orderBy('name', 'DESC')
->orderBy('email', 'ASC')
->get();
Produces the following query:
SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC
You can do as #rmobis has specified in his answer, [Adding something more into it]
Using order by twice:
MyTable::orderBy('coloumn1', 'DESC')
->orderBy('coloumn2', 'ASC')
->get();
and the second way to do it is,
Using raw order by:
MyTable::orderByRaw("coloumn1 DESC, coloumn2 ASC");
->get();
Both will produce same query as follow,
SELECT * FROM `my_tables` ORDER BY `coloumn1` DESC, `coloumn2` ASC
As #rmobis specified in comment of first answer you can pass like an array to order by column like this,
$myTable->orders = array(
array('column' => 'coloumn1', 'direction' => 'desc'),
array('column' => 'coloumn2', 'direction' => 'asc')
);
one more way to do it is iterate in loop,
$query = DB::table('my_tables');
foreach ($request->get('order_by_columns') as $column => $direction) {
$query->orderBy($column, $direction);
}
$results = $query->get();
Hope it helps :)
Use order by like this:
return User::orderBy('name', 'DESC')
->orderBy('surname', 'DESC')
->orderBy('email', 'DESC')
...
->get();
Here's another dodge that I came up with for my base repository class where I needed to order by an arbitrary number of columns:
public function findAll(array $where = [], array $with = [], array $orderBy = [], int $limit = 10)
{
$result = $this->model->with($with);
$dataSet = $result->where($where)
// Conditionally use $orderBy if not empty
->when(!empty($orderBy), function ($query) use ($orderBy) {
// Break $orderBy into pairs
$pairs = array_chunk($orderBy, 2);
// Iterate over the pairs
foreach ($pairs as $pair) {
// Use the 'splat' to turn the pair into two arguments
$query->orderBy(...$pair);
}
})
->paginate($limit)
->appends(Input::except('page'));
return $dataSet;
}
Now, you can make your call like this:
$allUsers = $userRepository->findAll([], [], ['name', 'DESC', 'email', 'ASC'], 100);
$this->data['user_posts'] = User_posts::with(['likes', 'comments' => function($query) { $query->orderBy('created_at', 'DESC'); }])->where('status', 1)->orderBy('created_at', 'DESC')->get();