How to use multiple OR,AND condition in Laravel query - sql

I'm new to laravel and I need help for query in laravel
My Custom Query: (Return Correct Result)
$centerid=$_POST['inputCenterStatus'];
$courseid=$_POST['inputCourseStatus'];
$sql1="SELECT * FROM xxstudentregistrationxx
WHERE
status='active'
AND
('$centerid'='' OR centerid='$centerid')
AND
('$courseid'='' OR courseid='$courseid')";

use DB;
public function get_registrations(Request $request){
if($request->has('inputCenterStatus')){
$centerid=$request->input('inputCenterStatus');
}else{
$centerid='';
}
if($request->has('inputCourseStatus')){
$courseid=$request->input('inputCourseStatus');
}else{
$courseid='';
}
$results=DB::table('xxstudentregistrationxx')
->where('status','active')
->where('centerid',$centerid)
->where('courseid',$courseid)
->get();
return response()->json($results);
}

You can use query builder conditional Clauses visit Conditional Clauses
.I hope you get help.

Related

Covert SQL to Laravel Query Builder

I'm a beginner regarding Laravel Query Builder, can you guys help me convert this SQL to Query Builder
public function check_available_room(Request $request, $checkin_date)
{
$available_rooms = DB::SELECT("SELECT * FROM rooms WHERE id NOT IN (SELECT room_id FROM bookings WHERE '$checkin_date' BETWEEN checkin_date AND checkout_date)");
}
Book model
function rooms() {
return $this->belongsTo(Room::class, 'room_id');
}
Room model
public function bookings() {
return $this->hasMany(Booking::class);
}
Thank you so much
Here is a solution if you have your models and relations in place
$availableRooms = Room::whereDoesntHave('bookings', function($bookingQuery) use ($checkin_date) {
$bookingQuery->where('checkin_date', '<', $checkin_date)
->where('checkout_date', '>=', $checkin_date);
})->get();
$unavailable_room_ids = Booking::where('checkin_date', '<', $checkin_date)
->where('checkout_date', '>=', $checkin_date)
->pluck('room_id')->get();
$available_rooms = Room::whereNotIn('id', $unavailable_room_ids)->get();

How count by the first letters in Laravel Query Builder?

I want to make a count by the first letters... I have this column
I would like to count each OE rows and each GICS rows
I'm working with this query
$data4 = DB::table('incidencias')
->select(DB::raw('grupo_asig as grupo_asig'), DB::raw('count(*) as number'))
->whereNotIn('grupo_asig', [''])
->groupBy('grupo_asig')
->orderBy('number', 'desc')
->get();
Use CASE WHEN and count the field like OE and ASIG
$data4 = DB::table('incidencias')
->select(DB::raw("(CASE WHEN grupo_asig LIKE 'OE%' THEN 'OE'
WHEN grupo_asig LIKE 'GICS%' THEN 'GICS'
END) AS grupo_asig_type"),
DB::raw('COUNT(*) as number'))
->whereNotIn('grupo_asig', [''])
->groupBy('grupo_asig_type')
->orderBy('number', 'desc')
->get();
You should try to use the [LIKE][1] function then and add it to your query:
->where('grupo_asig', 'like', 'OE%')
->where('grupo_asig', 'like', 'GICS%')
Edit:
I tried a lot around and came to this solution and made a SQL fiddle: http://sqlfiddle.com/#!9/06a39b/8
Does it help you?
You could use Collections. No real need to change your query much.
$data4 = DB::table('incidencias')
->select('grupo_asig')
->selectRaw('count(*) as number'))
->whereNotIn('grupo_asig', [''])
->groupBy('grupo_asig')
// ->orderBy('number', 'desc') Unless you use this array somewhere, it's not needed.
->get();
use Illuminate\Support\Str;
...
// php >= 7.4.0
$oe_count = $data4->filter(fn($data) => Str::startsWith($data->grupo, 'OE '))->count();
$gigs_count = $data4->filter(fn($data) => Str::startsWith($data->grupo, 'GIGS '))->count();
// php < 7.4.0
$oe_count = $data4->filter(function ($data) {
return Str::startsWith($data->grupo, 'OE ');
})->count();
$gigs_count = $data4->filter(function ($data) {
return Str::startsWith($data->grupo, 'GIGS ');
})->count();
Starting with Laravel 6, you can also use cursor() instead of get() in your query to return a LazyCollection. It's faster for this scenario.
I would suggest using a query for that:
refer to this answer
SELECT
LEFT(grupo_asig, 1) AS first_letter,
COUNT(*) AS total
FROM incidencias
GROUP BY first_letter

Laravel eloquent where with relationship

I am stuck on transforming this SQL query to an eloquent query in Laravel. The SQL query works (tested in Sequel) but I cannot write it in eloquent ...
SELECT faqs.question FROM faqs
JOIN categories c ON c.id = faqs.category_id
WHERE c.subsite = 'sport'
This is what I have tried so far, but it returns all the questions, (ignoring the subsite filter).
$cat = Faq::with(['category' => function($query) use ($subsite) {
$query->where('subsite', $subsite);
}])->get();
Thanks for the help
Try this
$cat = Faq::query();
if (isset($subsite) && !empty($subsite) {
$query->whereHas('category', function ($query) use ($subsite) {
$query->where('subsite', $subsite);
});
}
$query->with('category')->get();
as per you core sql query, here is your laravel query.
$data = DB::table('faqs')
->join('categories', 'categories.id', '=', 'faqs.category_id')
->select('faqs.question')
->where('categories.subsite', '=', 'sport')
->get();
Hope this will help you!

SQL query to Laravel

I am trying to convert the following query to Laravel:
select libéllé
from application
where libéllé not in (select application_id from application_user
where user_id = $id)
Laravel whereNotIn supports closures for subqueries, so it will be as simple as this:
Using Eloquent:
// Add this to top of your file.
use App\{ Application, ApplicationUser };
// Get your entries.
$rows = Application::whereNotIn('libéllè', function($query) use ($id) {
$query->select('application_id')->from((new ApplicationUser)->getTable())->where('user_id', $id);
})->get(['libéllè']);
Using Query Builder:
$rows = DB::table('application')->whereNotIn('libéllè', function($query) use ($id) {
$query->select('application_id')->from('application_user')->where('user_id', $id);
})->get(['libéllè']);
Please Try it.
$results = DB::select(
select libéllé
from application
where (libéllé)
not in(
select application_id from application_user
where user_id = $id
)
);
Also see this answer: How to convert mysql to laravel query builder
Also see this documentation: https://laracasts.com/discuss/channels/laravel/laravel5-resolve-username-from-2-tables?page=1

codeigniter change complex query into active record

I have a codeigniter app.
My active record syntax works perfectly and is:
function get_as_09($q){
$this->db->select('m3');
$this->db->where('ProductCode', $q);
$query = $this->db->get('ProductList');
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$row_set[] = htmlentities(stripslashes($row['m3'])); //build an array
}
return $row_set;
}
}
This is effectively
select 'm3' from 'ProductList' where ProductCode='$1'
What I need to do is convert the below query into an active record type query and return it to the controller as per above active record syntax:
select length from
(SELECT
[Length]
,CONCAT(([width]*1000),([thickness]*1000),REPLACE([ProductCode],concat(([width]*1000),([thickness]*1000),REPLACE((convert(varchar,convert(decimal(8,1),length))),'.','')),'')) as options
FROM [dbo].[dbo].[ProductList]) as p
where options='25100cr' order by length
I picture something like below but this does not work.
$this->db->select(length);
$this->db->from(SELECT [Length],CONCAT(([width]*1000),([thickness]*1000),REPLACE[ProductCode],concat(([width]*1000),([thickness]*1000),REPLACE((convert(varchar,convert(decimal(8,1),length))),'.','')),'')) as options
FROM [dbo].[dbo].[ProductList]);
$this->db->where(options, $q);
$this->db->order(length, desc);
Help appreciated as always. Thanks again.
You can use sub query way of codeigniter to do this for this purpose you will have to hack codeigniter. like this
Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now subquery writing in available And now here is your query with active record
$select = array(
'Length'
'CONCAT(([width]*1000)',
'thickness * 1000',
'REPLACE(ProductCode, concat((width*1000),(thickness*1000),REPLACE((convert(varchar,convert(decimal(8,1),length))),'.','')),'')) as options'
);
$this->db->select($select);
$this->db->from('ProductList');
$Subquery = $this->db->_compile_select();
$this->db->_reset_select();
$this->db->select('length');
$this->db->from("($Subquery)");
$this->db->where('options','25100cr');
$this->db->order_by('length');
And the thing is done. Cheers!!!
Note : While using sub queries you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
Source