Laravel query with where and where - sql

I've trying to basically do two SQL requests into one laravel array.
These are my SQL
SELECT * FROM `transactions` WHERE `plan` LIKE '1050' ORDER BY `updated_at` DESC
SELECT * FROM `transactions` WHERE `user` LIKE '1050' ORDER BY `updated_at` DESC
I want to have all transaction that have "plan" == "1050" AND all transactions that have "user" == "1050" in one variable.
This is not working for me:
$ct=transactions::where('user',$user->id)
->orWhere('plan', $user->id)
->orderby('created_at',"asc")->get();

The context agnostic way to combine the results of two union compatible queries (such as yours) would be:
$result = transactions::where('plan', 'LIKE', $user->id)->orderBy('updated_at', 'DESC')
->union(
transactions::where('user', 'LIKE', $user->id)
->orderBy('updated_at', 'DESC')
)
->get();
This of course means that the results are ordered by plan then user. You can sort them by updated_at globally using the below function on the result:
$result = $result->sortBy('updated_at', 'DESC');
There's also a way to do it on the query level but I don't see much benefit since you're getting all the data anyway.
The above query should be functionally equivalent to:
$result = transactions::orWhere('plan', 'LIKE', $user->id)
->orWhere('user', 'LIKE', $user->id)
->orderBy('updated_at', 'DESC')
->get();
This will have the same results but in a different order than the union.

Related

exists query does not return relevant result

I have a Laravel application with this Eloquent query:
$products = Product::where('name', 'LIKE', "%{$value}%")
->whereHas('categories', function($q) {
$q->where( 'slug', 'tonery-cartridge' );
})->with('manufacturer')
->with('sm_image')
->orderBy('created_at','DESC')
->take(10)
->get();
This code generates the sql command like:
select * from `products` where `name` LIKE '%can%'
and exists (
select * from `categories` inner join `category_product`
on `categories`.`id` = `category_product`.`category_id`
where `products`.`id` = `category_product`.`product_id`
and `slug` = 'tonery-cartridge'
)
order by `created_at` desc limit 10
I am sure there are products which name contains "can" string and which belongs to the category with slug "tonery-cartridge". Why this query returns an empty result? If I try to make inner join sql manually it works well as on the screenshot below:
I think that your queries are not equivalent. The SQL output from laravel does not join tables in it's FROM clause, but in your manually constructed SQL statement you do a lot of inner joins in your FROM clause and on the resulting table you perform your operations, which is not true for the former.
Try the following
DB::table('products')
->join('category_product', 'category_product.product_id', '=', 'products.id')
->join('categories', 'category_product.category_id', '=', 'categories.id')
->whereRaw('products.name LIKE %can% AND categories.slug = "tonery-cartridge"')
->select('products.name', 'categories.slug')
->orderBy('created_at','DESC')
->take(10)
->get()
If you want to avoid using whereRaw, you can try the following.
DB::table('products')
->join('category_product', 'category_product.product_id', '=', 'products.id')
->join('categories', 'category_product.category_id', '=', 'categories.id')
->where([
['products.name, 'LIKE', '%' . $value . '%'],
['categories.slug', '=', 'tonery-cartridge']])
->select('products.name', 'categories.slug')
->orderBy('created_at','DESC')
->take(10)
->get()
HTH
This could be one of the solutions
$category = Category::where( 'slug', 'tonery-cartridge' )->first();
$products = $category->products()
->where('name', 'LIKE', "%{$value}%")
->with('manufacturer')
->with('sm_image')
->latest()
->take(10)
->get();

cannot group with eloquent with PostreSQL

Here's my Eloquent query:
$visits = Visit::orderBy('date', 'desc')->groupBy('user_id')->get(['date', 'user_id']);
But posgreSQL is refusing the query, telling me:
SQLSTATE[42803]: Grouping error: 7 ERROR: column "visits.date" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: select "date", "user_id" from "visits" group by...
the same stuff works on MySQL when I disable ONLY_FULLY_GROUP_BY
what can I do to make it work? It would be great if I didn't have to edit configs, just the code.
This selects the latest date for each user_id:
$sub = Visit::select('user_id', DB::raw('max("date") "date"'))->groupBy('user_id');
$sql = '(' . $sub->toSql() . ') as "sub"';
$visits = Visit::join(DB::raw($sql), function($join) {
$join->on('visits.user_id', 'sub.user_id')
->on('visits.date', 'sub.date');
})->orderBy('visits.date', 'desc')->get(['visits.date', 'visits.user_id']);
If there are multiple visits for a user_id and date combination, the query returns all of them. Removing the duplicates is possible, but makes the query more complex.
It's easier to remove them afterwards:
$visits = $visits->unique('user_id');
Using postgre sql you could use distinct on user_id and order your date column to pick latest date per user_id, In laravel you could raw expression
$visits = Visit::select(DB::raw('distinct on (user_id)'), 'date')
->orderBy('date', 'desc')
->get();
Demo

Laravel Query Builder Statement return no result, but sql statement does

Laravel Query Builder
$data = CustomerPrepaid
::join('pos_sales', 'customer_prepaid.customer_id', '=', 'pos_sales.customer_id')
->join('pos_sales_product', 'pos_sales.pos_sales_code', '=', 'pos_sales_product.pos_sales_code')
->where('pos_sales_product.product_id', 'customer_prepaid.product_id')
->select('customer_prepaid.customer_id', 'customer_prepaid.created_at',
'pos_sales_product.pos_sales_product_code as reference_no',
'customer_prepaid.product_id', 'customer_prepaid.balance',
'last_used', 'expiry_date', 'customer_prepaid.amount as price')
->offset(($page-1)*$limit)->limit($limit)->get();
SQL
SELECT customer_prepaid.customer_id, customer_prepaid.created_at as purchase_date,
pos_sales_product.pos_sales_product_code as reference_no, customer_prepaid.product_id,
customer_prepaid.balance, customer_prepaid.amount*customer_prepaid.balance as value,
last_used, expiry_date, customer_prepaid.amount as price,
customer_prepaid.amount*customer_prepaid.balance as total
FROM customer_prepaid
JOIN pos_sales ON customer_prepaid.customer_id = pos_sales.customer_id
JOIN pos_sales_product ON pos_sales.pos_sales_code = pos_sales_product.pos_sales_code
WHERE pos_sales_product.product_id = customer_prepaid.product_id
The resulting SQL executed on the server returns the right result, but I get no eloquent result, why might that be?
Oh gosh, took me forever to realize you misused ->where.
Change your ->where to ->whereColumn:
$data = CustomerPrepaid
::join('pos_sales', 'customer_prepaid.customer_id', '=', 'pos_sales.customer_id')
->join('pos_sales_product', 'pos_sales.pos_sales_code', '=', 'pos_sales_product.pos_sales_code')
->whereColumn('pos_sales_product.product_id', 'customer_prepaid.product_id')
->select(
'customer_prepaid.customer_id',
'customer_prepaid.created_at',
'pos_sales_product.pos_sales_product_code as reference_no',
'customer_prepaid.product_id', 'customer_prepaid.balance',
'last_used', 'expiry_date', 'customer_prepaid.amount as price'
)
->offset(($page-1)*$limit)
->limit($limit)
->get();
You have to use whereColumn instead of where to make column comparison. Else it's expecting a third parameter value to be set.
Check the documentation on how to use whereColumn: https://laravel.com/docs/5.5/queries#where-clauses

How can I do this SQL in Query builder laravel

How can I do this SQL in Query builder laravel
select Doctor_id from doctors where Doctor_id NOT IN
(SELECT Doctor_id from report_reviewers WHERE Report_id = 26 )
Try with this
$result = DB::table('doctors')
->whereNotIn('doctor_id', function($q){
$q->from('report_reviewers')
->select('Doctor_id')
->where('Report_id', '=', 26)
})
->select('doctor_id')
->get();
Whenver in doubt, if you know the raw SQL, you can simply do
$query = 'select Doctor_id from doctors ...';
$result = DB::select($query);
Also, all credit goes to this genius How to create a subquery using Laravel Eloquent?
Update
The missing argument comes from the closure you are using
->whereNotIn('doctor_id', function($q,$id){
$q->from('report_reviewers')
->select('Doctor_id')
->where('Report_id',$id);
})
You need to pass the $id variable like this
->whereNotIn('doctor_id', function($q) use ($id) {
$q->from('report_reviewers')
->select('Doctor_id')
->where('Report_id',$id);
})
Try again and see.

Specifying a WHERE clause after a JOIN clause - Active Record - CodeIgniter

I wanted to ask is it possible to specify a where clause after a join in order to match data to a users input. Say for example I have the following code:
$this->db->select('user.*,role.*')
$this->db->from('user');
$this->db->where('user.username', $username);
$this->db->where('user.password', $password);
$this->db->join('role','role.id = user.role_id')
$result = $this->db->get();
and I want to query the matching data from the table 'role':
$this->db->select('user.*,role.*')
$this->db->from('user');
$this->db->where('user.username', $username);
$this->db->where('user.password', $password);
$this->db->join('role','role.id = user.role_id')
$this->db->where('role.speaker', $speaker); //want to know if this is correct
$result = $this->db->get();
Is this possible? Can I compare results (using WHERE) after a JOIN? Will that produce results matching to the WHERE clause?
Thanks!
CodeIgniter doesn't actually build the query until ->get() is called. You can call the methods in whatever order you want.