convert raw mySQL statement to laravel 4 eloquent with pagination - laravel

I'm trying to express MySQL statment in Eloquent with pagination
code:
$query = "(SELECT city_name FROM Cities WHERE city_name LIKE '%" .
$keyword . "%')
UNION
(SELECT area_name FROM Areas WHERE area_name LIKE '%" .
$keyword . "%')
UNION
(SELECT sub_location_name FROM Sub_locations WHERE sub_location_name LIKE '%" .
$keyword . "%' )";

Try This :
$cities = DB::table('Cities')->select('city_name')->where('city_name', $keyword);
$area=DB::table('Areas')->select('area_name')->where('area_name', $keyword);
$result=DB::table('Sub_locations')
->select('sub_location_name')
->where('sub_location_name', $keyword)
->union($cities)
->union($area)
->paginate(15);

Related

Multiple where condition does not work o n the Laravel eloquent

I am new to Laravel. I am writing an Eloquent query but it does not work.
the code is
$stories = Stories::with(['user', 'comment'])
->where('blocked', 1)
->where('title', 'like', '%' . $request->title . '%')
->orWhere('story', 'like', '%' . $request->story . '%')
->orWhere('section', 'like', '%' . $request->section . '%')
->orWhere('tags', 'like', '%' . $request->tags . '%')
->orderBy('id', 'DESC')
->get();
but it returns with 'blocked', 0
How can I get the result with 'blocked', 1 as well as the Search value?
You have an order of operations issue. Consider using this version:
$stories = Stories::with(['user', 'comment'])
$query->where('blocked', 1)
->where(function($query) {
$query->where('title', 'like', '%' . $request->title . '%')
->orWhere('story', 'like', '%' . $request->story . '%')
->orWhere('section', 'like', '%' . $request->section . '%')
->orWhere('tags', 'like', '%' . $request->tags . '%')
})
->orderBy('id', 'desc')
->get();
Here is the raw query you currently running:
SELECT *
FROM stories
WHERE (blocked = 1 AND
title LIKE ?) OR
story LIKE ? OR
section LIKE ? OR
tags LIKE ?
ORDER BY id DESC;
Note carefully that I have included parentheses, as the query will actually be evaluted. Here is the version you really want, corresponding to the above Eloquent code:
SELECT *
FROM stories
WHERE blocked = 1 AND
(title LIKE ? OR
story LIKE ? OR
section LIKE ? OR
tags LIKE ?)
ORDER BY id DESC;
Since you need blocked with other fields where you should use advanced query
https://laravel.com/docs/8.x/queries#subquery-where-clauses
$stories = Stories::with(['user', 'comment'])
->where('blocked', 1)
->where(function($q) use ($request) {
$q->where('title', 'like', '%' . $request->title . '%')
->orWhere('story', 'like', '%' . $request->story . '%')
->orWhere('section', 'like', '%' . $request->section . '%')
->orWhere('tags', 'like', '%' . $request->tags . '%');
})->orderBy('id', 'DESC')->get();

How to use multiple WHERE in DB::select in Laravel

Here is the original code:
$invoice = DB::select('SELECT MAX(CAST(`invoice_number` as UNSIGNED)) as invoice_number FROM `invoices` where company_id = "' . company()->id . '" ');
return $invoice[0]->invoice_number;
The above works great, but I want to use it like this:
$invoice = DB::select('SELECT MAX(CAST(`invoice_number` as UNSIGNED)) as invoice_number FROM `invoices` where company_id = "' . company()->id . '" where depa_series = "2" ');
return $invoice[0]->invoice_number;
But this gives the following error:
Illuminate\Database\QueryException
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server version for the right syntax
to use near ' where depa_series = "2"' at line 1 (SQL: SELECT MAX(CAST(`invoice_number` as UNSIGNED)) as invoice_number FROM `invoices` where company_id = "140", where depa_series = "2" )
How to use multiple WHERE clauses in DB::select?
Thank you!
The query gives a syntax error, because you use where twice.
Try to change it to this, by using the AND condition:
DB::select('SELECT MAX(CAST(`invoice_number` as UNSIGNED)) as invoice_number FROM `invoices` where company_id = "' . company()->id . '" AND depa_series = "2"');
Have a look at the selectRaw method
$invoice = DB::table('invoices')
->selectRaw('MAX(CAST(invoice_number as UNSIGNED)) as invoice_number')
->where('company_id', company()->id)
->where('depa_series', "2")
->get();
return $invoice[0]->invoice_number;
here is what you should do
$invoice =
DB::table('invoices')
->selectRaw('MAX(CAST(invoice_number as UNSIGNED)) as invoice_number')
->where(['company_id', company()->id, 'depa_series', "2"])
->get(); return $invoice[0]->invoice_number;
There will no need to using multiple where statements. You can just put all in an array.

I Create mysql query but i not get pagination how to use laravel paginate in this query

I've created MySQL query for searching results. The query works properly but if I use laravel pagination on this query I get an error
Call to a member function paginate() on array ,
How to solve this with pagination?
$search = \DB::SELECT("SELECT l.*,
r.id AS reservation_id,
r.status AS res_status,
r.start_date,
r.end_date,
Avg(r.rating) AS rating
FROM listings l
LEFT JOIN reservations r ON r.listing_id = l.id
WHERE ( ( Cast('" . $search_date . "' AS date) NOT BETWEEN r.start_date AND r.end_date ) OR r.status = 'Cancel' )
AND l.city_id = $city_id
AND l.persons >= $guests
AND l.listing_type_id = $type
GROUP BY l.id
ORDER BY r.rating DESC
");
DB::select() will return an array. You could probably convert your query to a Query Builder and then use paginate() on it. For example:
$search = DB::table('listings')
->selectRaw('listings.*, reservations.id AS reservation_id, reservations.status AS res_status, reservations.start_date, reservations.end_date, AVG(reservations.rating) as rating')
->leftJoin('reservations', 'reservations.listing_id', 'listings.id')
->whereRaw("(CAST(? AS date) NOT BETWEEN reservations.start_date AND reservations.end_date) or reservations.status = 'Cancel'", [$search_date])
->where('listings.city_id', '=', $city_id)
->where('listings.persons', '>=', $guests)
->where('listings.listing_type_id', '=', $type)
->groupBy('listings.id')
->orderBy('reservations.rating', 'DESC')
->paginate(10);

Using 'like' on 2 SQL columns combined

I currently have 2 columns in my table going by the name of uploadDate and uploadTime. I have a clause like this:
->orWhere('uploadDate', 'like', '%' . $request->search . '%')
->orWhere('uploadTime', 'like', '%' . $request->search . '%');
The problem is that if $request->search = yyyy-mm-dd, hh:mm:ss, my web app is not able to get any results since uploadDate and uploadTime are seperate columns on the DB. Does anyone have a way of creating a orWhere statement that concatinates both uploadDate and uploadTime?
I know this can be easily achieved by just creating a single column in the DB that merges both columns but I'm just looking for an easier way out at this point, hahaha.
You shouldn't use like or orWhere() here if you want to find records by exact date and time.
->where('uploadDate', str_before($request->search, ','))
->where('uploadTime', str_after($request->search, ', '))
If you have other where() or orWhere() clauses in the query, you can do this:
->where([
'uploadDate', '=', str_before($request->search, ','),
'uploadTime', '=', str_after($request->search, ', ')
])

Multi column select query

my table field are
payid payamount paytype
01 5000 1
02 3000 1
03 2500 3
I want to get result as select cash =(select sum (payamount)where paytype=1)
online=(select sum (payamount)where paytype=2)
check=(select sum (payamount)where paytype=3)
how I can do it in codeigniter?
may be you are looking for the following
$this->db->select("SUM(payment)")
->from("TABLE_NAME")
->where("paytype", $paytype)
put the TABLE_NAME and pass the $paytype and hope it will work...
Sounds like a GROUP BY.
SELECT sum(paymount), paytype FROM mytable GROUP BY paytype;
In Codeigniter you can use
$this->db->select_sum('paymount');
$this->db->select('paytype');
$this->db->group_by('paytype');
$query = $this->db->get('mytable');
public function getincomebyyear($s,$e){
$this->db->select('income_id, income_date,income_source,income_sourceid,income_refferanceid,income_description,income_amount,(select sum(income_amount) from tbl_incomes where income_description=1) as cash,'
. '(select sum(income_amount) from tbl_incomes where income_description=2) as online,'
. '(select sum(income_amount) from tbl_incomes where income_description=3) as che');
$this->db->from('tbl_incomes');
$this->db->where('income_date between'
. ' "'. date('Y-m-d', strtotime($s)). '" and'
. ' "'. date('Y-m-d', strtotime($e)).'"');
$query_result= $this->db->get();
$result=$query_result->result();
return $result;
}

Resources