Get data whereBeetween two coloms - php

I'm using Laravel 5.5.
I have Table centrals with Model Centrals
and table like this
my Controller
$from = $request->year_from;
$to = $request->year_to;
$month_from = $request->month_from;
$month_to = $request->month_to;
$param = $request->get('parameters_id', []);
$search = Centrals::whereIn('parameters_id', $param)
->where('type', 'Monthly')
->where('year', $from)
->whereBetween('months_id', [$month_from, $month_to])
->orderBy('year')
->get();
now how i get data
example request:
$request->year_from = 2016;
$request->month_from = 1; /* 1 =Jan*/
$request->year_from = 2018;
$request->month_from = 3; /* 3 =Mar*/

The following should do the trick:
$search = Centrals::whereIn('parameters_id', $param)
->where('type', 'Monthly')
->where(function($q) use ($yearFrom, $monthFrom) {
$q->where('year', '>', $yearFrom);
$q->orWhere(function($q2) use ($yearFrom, $monthFrom) {
$q2->where('year', $yearFrom);
$q2->where('month', '>=', $monthFrom);
});
})
->where(function($q) use ($yearTo, $monthTo) {
$q->where('year', '<', $yearTo);
$q->orWhere(function($q2) use ($yearTo, $monthTo) {
$q2->where('year', $yearTo);
$q2->where('month', '<=', $monthTo);
});
})->get();

Related

Laravel Eloquent complex where

How to convert this code to Laravel (Eloquent):
$query = 'SELECT * FROM posts p WHERE (p.is_public = 1)';
if (isset($date)){ //$date format is '2018-09-01 00:00:00'
$query .= ' AND (p.created_at > "'.$date.'")';
}
if (isset($search)){
$query .= ' AND ((p.title LIKE "%'.$search.'%") OR (p.body LIKE "%'.$search.'%"))';
}
try this:
assume Post is your model
$posts = Post::where('is_public', 1);
if (isset($date)) {
$posts->where('created_at', '>', $date);
}
if (isset($search)) {
$posts->where(function($query) use ($search) {
$query->where('title', 'like', "%'.$search.'%")
->orWhere('body', 'like', "%'.$search.'%");
});
}
$posts = $posts->get();
This is Example code : assume Post is your model
$getPosts=Post::query()->where('is_public',1);
$getPosts->when(isset($date),function($q) use ($date){
$q->where('created_at','>',$date);
});
$getPosts->when(isset($search),function($q) use ($search){
$q->where('title','like','%'.$search.'%');
$q->orWhere('body','like','%'.$search.'%');
});
$posts=$getPosts->get();
You should try this:
$query = Post::where('is_public', '1');
if (isset($date)){ //$date format is '2018-09-01 00:00:00'
$query->where('created_at', '>', $date);
}
if (isset($search)){
$query->whereRaw('title LIKE "%'.$search.'%" OR body LIKE "%'.$search.'%"');
}
$posts = $query->get();

SQL: Query returns 1 using count

I have a query in PHP(MySQL). I am fetching records from a table and returning them to a datatable.
The problem is it always returns 1 when I use count() with the query.
However, if I count the elements of the array, then the result is as expected. It returns all 8 records.
Following is my code:
public function job_order_detail_del($arr=array()) {
$count = 0;
$start = isset($arr['start'])?$arr['start']:0;
$length = isset($arr['length'])?$arr['length']:0;
$search = isset($arr['search'])?$arr['search']:'';
$orderBy = isset($arr['orderBy'])?$arr['orderBy']:'';
$orderDir = isset($arr['orderDir'])?$arr['orderDir']:'';
$aufnr = isset($arr['aufnr'])?$arr['aufnr']:0;
$aufpl = isset($arr['aufpl'])?$arr['aufpl']:0;
$type = isset($arr['type'])?$arr['type']:'';
$whr = array('h.stats' => '', 'h.bukrs' => Session::get('company'), 'h.delstats' => '');
if ($aufnr > 0)
$whr['a.aufnr'] = $aufnr;
if ($aufpl > 0)
$whr['a.aufpl'] = $aufpl;
$a = DB::table('zpp_afpo_h as h')
->leftjoin('zpp_afpo as a ', function($join) {
$join->on('a.aufnr', '=', 'h.aufnr')
->where('a.bukrs', '=', Session::get('company'))
->where('a.stats', '=', '');
})
->leftjoin('zpp_afvc as b ', function($join) {
$join->on('a.aufnr', '=', 'b.aufnr')
->on('a.aufpl', '=', 'b.aufpl')
->where('b.bukrs', '=', Session::get('company'))
->where('b.stats', '=', '');
})
->leftjoin('zpp_afru as c ', function($join) use($type) {
$join->on('c.aufnr', '=', 'b.aufnr')
->on('c.rueck', '=', 'b.rueck');
})
->where('c.type', '=', $type)
->where('c.bukrs', '=', Session::get('company'))
->where('c.stats', '=', '')
->where('c.delstats', '=', '')
->select('h.idat2', 'a.matnr', 'b.arbpl', 'a.gamng as total', 'b.rueck', 'h.priority', 'b.vornr', 'b.prev_startper', 'b.scrap', 'h.dispatch_date', 'h.order_start_dt', 'h.requirement_dt', 'h.ktxt', 'c.rmzhl', 'c.budat', 'c.aufnr', 'c.rework_lmnga', DB::raw('sum(c.lmnga) as sum_cnfrm'));
if ($aufnr == '') {
$a->where('h.idat2', '=', '0000:00:00');
}
$a->where($whr)
->groupby('b.rueck')
->groupby('c.rmzhl')
->groupby('c.counter');
if($orderBy!=''){
$a->orderBy($orderBy,$orderDir);
}
if($search!=''){
$dt_srch = implode('-',array_reverse(explode('-',$search)));
$a->where(function($query) use ($search,$dt_srch){
$query->where('c.aufnr','LIKE','%'.$search.'%')
->orWhere('a.matnr','LIKE','%'.$search.'%')
->orWhere('c.budat','LIKE','%'.$dt_srch.'%')
->orWhere('b.arbpl','LIKE','%'.$search.'%')
->orWhere('a.gamng','LIKE','%'.$search.'%');
});
}
if($length>0){
$get_rec = $a->skip($start)->take($length)->get();
}else{
$get_rec = $a->get();
$count = count($get_rec);
// $count = $a->count(); //Problem is here
return $count;
}
$arr = array();
foreach($get_rec as $l){
if($length>0 || Input::get('open') == 1 || Input::get('open') == 2){
$arr = DB::table('maras')
->where('matnr','=',$l->matnr)
->where('bukrs','=',Session::get('company'))
->where('stats','=','')
->where('delstats','=','')
->select(DB::raw('GROUP_CONCAT(distinct(matnr)) as mat'),DB::raw('GROUP_CONCAT(distinct(mdesc)) as mat_desc'))
->groupby('matnr')
->first();
$l->matnr = $arr->mat;
$l->mat_desc = $arr->mat_desc;
}
}
return $get_rec;
}
Please let me know the problem. Thanks in advance.
You are using count on groupBy element and count is returning only the grouped count. That's why it is returning only single row or 1. You could count the returned collections in this case like-
$count = $get_rec->count();

Convert SQL Query into Laravel query

I am trying to check the given input is already existed between the c_start and c_end through query, but it is not working. Here is my controller.. for example if person 1 booked a room from 10 to 12 then person can't book the same room at same date from 11 to 12 or any time between the existing booked time.
/* namespace App\booking; */
namespace App\Http\Controllers;
use App\booking;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use DB;
use App\Quotation;
use DateTime;
class RoombookController extends Controller {
public function insert_check(Request $request) {
$roomname = $request->input('roomname');
$book = $request->input('bookdate');
$dbstime = explode(':', $request->input('starttime'));
$dbetime = explode(':', $request->input('endtime'));
$dbstime[0] = $dbstime[0] * 60;
$dbetime[0] = $dbetime[0] * 60;
$dbsum = array_sum($dbstime);
$dbesum = array_sum($dbetime);
$users = DB::table("bookings")
->select("id")
->where('bookdate', '=', $request->input('bookdate'))
->where('roomname', '=', $request->input('roomname'))
->where(function ($query){
$query->where('c_start', '<', $dbsum);
$query->orWhere('c_end', '>', $dbsum);
})
->orWhere(function($query){
$query->where('c_start', '<', $dbesum);
$query->orWhere('c_end', '>', $dbesum);
});
if ($users->count() == 0) {
$booking = new booking;
$booking->bookdate = $request->input('bookdate');
$booking->roomname = $request->input('roomname');
$booking->starttime = $startTime = $request->input('starttime');
$booking->endtime = $finishTime = $request->input('endtime');
$booking->purpose = $request->input('Purpose');
$booking->booked_by = Auth::user()->id;
$smstime = explode(':', $startTime);
$emstime = explode(':', $finishTime);
$smstime[0] = $smstime[0] * 60;
$emstime[0] = $emstime[0] * 60;
$startsum = array_sum($smstime);
$endsum = array_sum($emstime);
$booking_time = $startTime . ' to ' . $finishTime;
$booking->c_start = $startsum;
$booking->c_end = $endsum;
$booking->booking_time = $booking_time;
$time = ($etime - $stime) / 60;
$booking->total_duration = $time;
$booking->save();
return view("bookmessage");
} else {
return view("duplicateValue");
}
}
}
Change query to:
$users = DB::table("bookings")
->select("id")
->where('bookdate', '=', $request->get('bookdate'))
->where('roomname', '=', $request->get('roomname'))
->where(function ($query) use ($dbsum, $dbesum){
$query->where(function ($query) use ($dbsum){
$query->where('c_start','<',$dbsum);
$query->Where('c_end','>',$dbsum);
})
->orWhere(function($query) use($dbesum){
$query->where('c_start','<',$dbesum);
$query->orWhere('c_end','>',$dbesum);
});
});
Try this code and let me know if it works:
$whereCondition = array('bookdate'=>$request->input('bookdate'),'roomname'=>$request->input('roomname'));
$users = DB::table("bookings")
->select("id")
->where($whereCondition)
->where(function ($query use $dbsum){
$query->where('c_start','<',$dbsum);
$query->orWhere('c_end','>',$dbsum);
})
->orWhere(function($query use $dbesum){
$query->where('c_start','<',$dbesum);
$query->orWhere('c_end','>',$dbesum);
})
->get();
You can run your sql query directly in laravel query builder .You can try this:
$sql = "SELECT * FROM `bookings` WHERE `bookdate`='2016-12-27' AND `roomname`='3' AND (($dbsum>`c_start` AND $dbsum<`c_end`) OR ($dbesum>`c_start` AND $dbesum<`c_end`))";
$result = DB::select(DB::raw($sql))
$result variable contains your output. You must be use your DB class
use DB;
this is the query from which i got my correct result
$whereCondition = array('bookdate'=>$request->input('bookdate'),'roomname'=>$request->input('roomname'));
$users = DB::table("bookings")
->select("id")
->where('bookdate', '=', $request->get('bookdate'))
->where('roomname', '=', $request->get('roomname'))
->whereRaw(DB::raw("((c_start<$dbsum and c_end>$dbsum) or (c_start<$dbesum and c_end>$dbesum ))"))
->get();

How we can join with where condition result through laravel eloquent?

I have situation in laravel 5.1 with eloquent. That is very hard for me at this time to get the solution.
I have 7 tables in database which are not related to each other, but I want to get results with joining them all and with where clause.
My Tables relations are:
lifegroups -> Campuses -> locations -> address
and
lifegroups -> grouptype -> groupuser -> user // this is confusing little bit
and
lifegroups -> schedule -> recurrance
Notice the lifegroup table is associated with multiple other tables.
My Existing Query is:
$campusGroups = DB::table('campuses')
->Join('lifegroups','campuses.f1_id', '=', 'lifegroups.campusId')
->Join('locations', 'locations.group_id', '=', 'lifegroups.f1Id')
->Join('addresses', 'addresses.location_id', '=', 'locations.id')
->Join('groups_users', 'groups_users.groupId', '=', 'lifegroups.id')
->Join('users', 'groups_users.userId', '=', 'users.id')
->distinct() //'users.first_name', 'users.last_name',
->select('lifegroups.*', 'campuses.name AS campusname', 'addresses.address', 'addresses.address2', 'addresses.city', 'addresses.province');
$groupLeaders = DB::table('campuses')
->Join('lifegroups', 'campuses.f1_id', '=', 'lifegroups.campusId')
->Join('groups_users', 'groups_users.groupId', '=', 'lifegroups.id')
->Join('users', 'groups_users.userId', '=', 'users.id')
->distinct()
->select('lifegroups.id', 'users.first_name', 'users.last_name');
$groupRecurrences = DB::table('campuses')
->Join('lifegroups', 'campuses.f1_id', '=', 'lifegroups.campusId')
->Join('schedules', 'schedules.event_id', '=', 'lifegroups.eventid')
->Join('recurrences', 'recurrences.schedule_id', '=', 'schedules.id')
->distinct()
->select('recurrences.occurOnFriday', 'recurrences.occurOnSaturday', 'recurrences.occurOnMonday', 'recurrences.occurOnSunday', 'recurrences.occurOnThursday', 'recurrences.occurOnTuesday', 'recurrences.occurOnWednesday', 'recurrences.recurrenceFrequency', 'recurrences.recurrenceFrequencyMonthly', 'recurrences.recurrenceFrequencyWeekly', 'schedules.start_date', 'schedules.recurrence', 'lifegroups.id AS groupId');
if (Session::has('campus')){
$campusId = Session::get('campus');
$searchObj = $campusGroups->where('campuses.id', intval($campusId));
$groupLeaders = $groupLeaders->where('campuses.id', intval($campusId));
$groupRecurrences = $groupRecurrences->where('campuses.id', intval($campusId));
$searchArray['campusId'] = $campusId;
}
if (Session::has('gender')){
$gender = Session::get('gender');
$searchObj = $campusGroups->where('lifegroups.gender', $gender);
$groupLeaders = $groupLeaders->where('lifegroups.gender', $gender);
$groupRecurrences = $groupRecurrences->where('lifegroups.gender', $gender);
$searchArray['gender'] = $gender;
} else {
$searchArray['gender'] = 'N/A';
}
if (Session::has('marital_status')){
$marital_status = Session::get('marital_status');
$searchObj = $campusGroups->where('lifegroups.marital_status', $marital_status);
$groupLeaders = $groupLeaders->where('lifegroups.marital_status', $marital_status);
$groupRecurrences = $groupRecurrences->where('lifegroups.marital_status', $marital_status);
$searchArray['marital_status'] = $marital_status;
} else {
$searchArray['marital_status'] = 'N/A';
}
if (Session::has('age')){
$age = Session::get('age');
$searchObj = $campusGroups->where('lifegroups.startAgeRange', $age);
$groupLeaders = $groupLeaders->where('lifegroups.startAgeRange', $age);
$groupRecurrences = $groupRecurrences->where('lifegroups.startAgeRange', $age);
$searchArray['age'] = $age;
} else {
$searchArray['age'] = 'N/A';
}
if (Session::has('keyword')){
$keyword = Session::get('keyword');
$searchObj = $campusGroups->where('lifegroups.name', 'Like', '%'. $keyword . '%');
//->orWhere('lifegroups.description', 'Like', '%'.$keyword.'%')
//->orWhere('users.first_name', 'Like', '%'.$keyword.'%');
$groupLeaders = $groupLeaders->where('lifegroups.name', 'Like', '%'. $keyword . '%');
$groupRecurrences = $groupRecurrences->where('lifegroups.name', 'Like', '%'. $keyword . '%');
$searchArray['keyword'] = $keyword;
} else {
$searchArray['keyword'] = 'N/A';
}
$campusGroupsTemp = $campusGroups->get();
$campusGroups = [];
$recurrenceGroups = [];
$groupLeaders = $groupLeaders->get();
$groupRecurrences = $groupRecurrences->get();
So this is a very long process and I can't add further search filters. Do you guys have any better idea how to do it with Laravel Eloquent, like
Lifegroups::with(['campuses', 'locations', 'addresses', 'grouptype', 'groupuser', 'users', 'schedules', 'recurrences'])
->where(['lifegroups.name', '=' 'name_value'],['lifegroups.description','like', '%like_valie%'], ['user.first_name', 'like', 'first_name_value'])
->get()->toArray();
If you are confused like me then only let me know how to do below mentioned thing with above type of tables scenario.
This becomes very easy with Eloquent assuming you have your models setup correctly. Just use dot notation to handle the nesting.
$data = Lifegroups::with([
'campuses.locations.address',
['grouptype.groupuser.user', function($q) use ($first_name) {
// Handle the constraints on the users table here.
$q->where('name', 'like', $first_name)
}],
'schedule.recurrance'
])
// Handle any constraints on the Lifegroups table here
->where('name', '=', 'name_value')
->where('description','like', '%like_valie%')
->get();
If you need to add more constraints for different tables, just add another parameter to the array we passed into the with function going as deep as you need to with the nexting and passing in a function with it where you will set the constraints like I did the users table.

Laravel dynamic queries with premade string

How to insert strings as query in Laravel? I have to handle a dynamic value for "book formats" (such as "pdf", "epub", "physical", "") and this formats are separated by comma. Here is my code:
$formats_sql = '';
$format_filter_count = 0;
$format_filter = explode(',', $format_filter);
foreach ($format_filter as $format_filter_tmp) {
if ($format_filter_count == 0) {
$formats_sql .= "where('format', '=', '{$format_filter_tmp}')";
} else {
$formats_sql .= "->orWhere('format', '=', '{$format_filter_tmp}')";
}
$format_filter_count += 1;
}
if ($price_filter == 'paid') {
$books = Book::where('book_id', '=', $category_book->book_id)->$formats_sql->where('sell_price', '>', '0')->where('status', '=', '1')->get();
}
But makes this problem:
Undefined property: Illuminate\Database\Eloquent\Builder::$where('format', '=', 'pdf')->orWhere('format', '=', 'epub')
Your over complicating this. You should be using whereIn where you need to search for an array of values.
You whole code above can be condensed to:
if ($price_filter == 'paid') {
$formats = explode(',', $format_filter);
Book::where('book_id', $category_book->book_id)->whereIn('format', $formats)->where('sell_price', '>', '0')->where('status', '1')->get();
}

Categories