How to use multiple WHERE in DB::select in Laravel - 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.

Related

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);

Laravel 5.2 orderBy relation withCount results in SQL error because of failed attempt to get column instead of count

The goal is to sort my campaigns by views in my filtration, which is why i have an analytics table with relations to my campaigns
My campaign model (The DB name is "ads"):
public function views() {
return $this->hasMany('App\Analytic', 'foreign_id', 'id')->where('foreign_type', '=', 'campaign');
}
The controller of my filtration:
$query = Ad::withCount('views')->with('tags');
$query->where("is_active", "=", 1);
$query->where("status", "=", 1);
$query->orderBy('views_count', 'DESC');
$campaigns = $query->get();
Now the reason for not writing it without the $query-> part, is because the query has lots of if statements depending on filtration settings.
The error im getting:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'views_count' in 'order clause' (SQL: select count(*) as aggregate from `ads` where `is_active` = 1 and `status` = 1 and `from_year` >= 7 and `to_year` <= 88 and `price` >= 1000 and `price` <= 64000 order by `views_count` desc)
The error is it tries to fetch a column, but i can't figuere out why.
If i try to access $campaign->views_count in my blade template, it shows the count just fine.
Thank you for your time, i hope someone can tell me what I'm doing wrong here.
The error you're getting is a result of a count() method not a get().
something like this
$query = Ad::withCount('views')->with('tags');
$query->where("is_active", "=", 1);
$query->where("status", "=", 1);
$query->orderBy('views_count', 'DESC');
$campaignCount = $query->count();
wich replaces the complex select part with:
select count(*) as aggregate
if you need the count() and the get(), do it like this:
$query = Ad::withCount('views')->with('tags');
$query->where("is_active", "=", 1);
$query->where("status", "=", 1);
$campaignCount = $query->count();
$query->orderBy('views_count', 'DESC');
$campaigns = $query->get();

Codeigniter 3 - Query Builder 'join' Method '!=' operator is not giving expected output

Not a Duplicate Question!!!
I am using CodeIgniter 3 - Query Builder Class with MySQLi.
Tables in DB:
'category_level_1' Table:
'category_level_2' Table:
Query in model.php:
$query = $this->db
->select('category_level_1.id, category_level_1.category')
->from('category_level_1')
->join('category_level_2', 'category_level_2.cat_lvl1_id != category_level_1.id', 'inner')
->group_by('category_level_1.id')
->get();
Output :
Inner-Join not working.
Expected Output :
Only need to output records in 'category_level_1' Table which are not related with 'category_level_2' Table.
Issue:
As showed above, output values are not as expected according to '!=' operator is not working with 'inner' join.
Hope this will help you :
$sql = "SELECT id, category
FROM category_level_1
WHERE id NOT IN (SELECT DISTINCT cat_lvl1_id FROM category_level_2)";
$query = $this->db->query($sql);
print_r($query->result());
Output :
Array
(
[0] => stdClass Object
(
[id] => 93
[category] => dummy
)
)
I suggest you try using a left orright join and a where clause. Give the following a go:
$query = $this->db
->select('category_level_1.id, category_level_1.category')
->from('category_level_1')
->join('category_level_2', 'category_level_2.cat_lvl1_id = category_level_1.id', 'left')
->where('category_level_2.cat_lvl1_id IS NULL')
->group_by('category_level_1.id')
->get();
$query = $this->db ->select('category_level_1.id, category_level_1.category') ->from('category_level_1') ->join('category_level_2', 'category_level_2.cat_lvl1_id <> category_level_1.id', 'inner') ->group_by('category_level_1.id') ->get();

Using a helper function to change a field of a query in Laravel 4 using DB:raw

I have a query function that I am using to pull some data from my database. I also have a function that changes around the "created_at" field to print it like so: Month Day YY'
Here is the query function:
public static function friend_activity_json($start = 0, $number_of_posts = 2) {
$friend_activity = DB::table('fanartists')
->join('fans', 'fanartists.fan_id', '=', 'fans.id')
->join('artists', 'fanartists.artist_id', '=', 'artists.id')
->orderBy('fanartists.created_at', 'DESC')
->select(DB::raw('StringEdit::getDate(fanartists.created_at) as created_at, fans.fbid, fans.first_name, fans.last_name, fans.gender, fans.city, fanartists.artist_id, artists.stage_name'))
->get();
The function is in the folder helpers, in a filed called "StringEdit.php". The function is getDate:
public static function getDate($date) {
$full_date = explode(" ", $date);
$date_pieces = explode("-", $full_date[0]);
$year = substr($date_pieces[0], -2);
$monthNum = $date_pieces[1];
$monthName = date("F", mktime(0, 0, 0, $monthNum, 10));
$final_date = $monthName ." ". $date_pieces[2] ." '".$year;
return $final_date;
}
I have been able to call this function elsewhere, so I know it works. How do I get it to work in this context to change around my "created_at" field? When running this I get the error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '::getDate(fanartists.created_at) as created_at, fans.fbid, fans.first_name, fans' at line 1 (SQL: select StringEdit::getDate(fanartists.created_at) as created_at, fans.fbid, fans.first_name, fans.last_name, fans.gender, fans.city, fanartists.artist_id, artists.stage_name from `fanartists` inner join `fans` on `fanartists`.`fan_id` = `fans`.`id` inner join `artists` on `fanartists`.`artist_id` = `artists`.`id` order by `fanartists`.`created_at` DESC) (Bindings: array ( ))
EDIT: New Error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"%M %d %y) as created_at, fans.fbid, fans.first_name, fans.last_name, fans.gende' at line 1 (SQL: select DATE_FORMAT(fanartists.created_at, "%M %d %y) as created_at, fans.fbid, fans.first_name, fans.last_name, fans.gender, fans.city, fanartists.artist_id, artists.stage_name from `fanartists` inner join `fans` on `fanartists`.`fan_id` = `fans`.`id` inner join `artists` on `fanartists`.`artist_id` = `artists`.`id` order by `fanartists`.`created_at` DESC) (Bindings: array ( ))
This won't work like the way you used it in your query here
DB::raw('StringEdit::getDate(fanartists.created_at) as created_at, fans.fbid, fans.first_name, fans.last_name, fans.gender, fans.city, fanartists.artist_id, artists.stage_name')
Here, getDate function is being treated as mysql function and it's not valid, anyways, you can use mysql's native DATE_FORMAT function instead, like
DATE_FORMAT(fanartists.created_at, "%M %d %y") as created_at
Check the documentation.

Using subquery in Doctrine 1.2

I'm having alot of trouble using a subquery in an update statement in doctrine 1.2
I want to set a field to the result of a subquery, but it seems impossible.
This is what i tried sofar.
$query = Doctrine_Query::create()->from('Users_Model_Book b');
$subSelect = $query->createSubquery()->select('ROUND(SUM(br.rating) / COUNT(br.id))')->from('b.BookRating')->where('b.BookRating.book_id = b.id');
$query->update()->set('bookrating', '('.$subSelect->getDql().')')->where('b.id = ?', $this->id)->getRawSql();
Will give 'Unknown component alias br'
$q = new Doctrine_RawSql();
$q ->addComponent('b', 'Users_Model_Book')
->addComponent('br', 'Users_Model_BookRating')
->update('b')
->set('b.bookrating', 'ROUND(SUM(br.rating) / COUNT(br.id)')
->where('b.id = ' . (bool) $this->id);
echo $q->getSqlQuery();
Will return SELECT b.id AS b_id, br.id AS br_id FROM b WHERE b.id = 1
Anybody that can help me?

Resources