Laravel Eloquent Where not working after joining table - php

Hi I have written a little query which doesnt seem to working when I use Eloquent but works when I write something similar in MySQL. Data isnt being retuned which shouldnt be due to my where clauses.
I have written this query which isnt working as expected -
$invoices = Invoice::leftJoin('user_details', 'invoices.user_id', 'user_details.user_id')
->where('invoices.practice_id', '!=', 'user_details.practice_id')
->first();
It is returning data where the invoice.practice_id = user_details.practice_id
I altered the query to prove it isnt working -
$invoices = Invoice::select('invoices.practice_id', 'user_details.practice_id')
->leftJoin('user_details', 'invoices.user_id', 'user_details.user_id')
->where('invoices.practice_id', '!=', 'user_details.practice_id')
->first();
The values returned the practice_id is 6, 6 which shouldnt be possible due to the following where clause where('invoices.practice_id', '!=', 'user_details.practice_id')
Have I done something wrong which I am just not seeing?
Thank you for any help you can provide!
UPDATE
Here is the DB schema for the invoice table
Here is the the DB schema fro the user_details table
The expected result is mentioned above, no results should be returned if invoice_practice_id = user_details.practice_id

#Luke Rayner
Try by rewriting line ->leftJoin('user_details', 'invoices.user_id', 'user_details.user_id')
to
->leftJoin('user_details', 'invoices.user_id', '=', 'user_details.user_id')
If not try to print Last query and post it

Related

How to convert this MySQL query to Laravel?

Here my MySQL query (work in phpMyAdmin) :
SELECT workcenter, (SUM(w1+w2 +w3 +w4)/ (COUNT(DISTINCT(teknisi))*40*4) )*100 AS total FROM `team` GROUP by workcenter ORDER BY total
then, i try in Laravel Sintax like this below (not work) :
$sql = Team::groupBy('workcenter')->select('workcenter', \DB::raw('(SUM(w1+w2+w3+w4)/ (COUNT(DISTINCT(teknisi))*30*4) )*100 AS total'))
->OrderBy('total', 'Desc')
->get();
When i run the laravel sintax, its doesn't show any errors, but the output is nothing..
Please anyone help me to convert the MySQL query to Laravel Sintax. Thank you!
I think you are close enough, however, this doesn't look like a correct way to group by with Eloquent ORM. Try using raw expressions, something like this might work:
$sql = DB::table('team')
->select(DB::raw('workcenter, (SUM(w1+w2 +w3 +w4)/ (COUNT(DISTINCT(teknisi))*40*4) )*100 as total'))
->orderBy('total', 'desc')
->groupBy('workcenter')
->get();
More about raw expressions here - https://laravel.com/docs/6.x/queries#raw-expressions
Whenever I want to convert SQL query to Laravel I always change one column name, the laravel error report will show your current query and u can compare it to the SQL query

Laravel where with 2 tables

I'm trying to check the another table to remove the matches from the results but unable to figure this out.
$value = people::select(array('people.blog_id'))
->join('blocks', 'people.user_id', '=', 'blocks.blocker')
->where('people.user_id', $user->id)
->where('blocks.blocker', '!=', 'people.user_id')
->get()
->toArray();
What I am trying to achieve, is to strip away the results when getting user_id from people where blocker is found as well in the blocks table, but the following returns an empty array.
As per laravel doc
You may use the table method on the DB facade to begin a query. The table method returns a fluent query builder instance for the given table, allowing you to chain more constraints onto the query and then finally get the results using the get method.
Change your query statement like bellow-
$articles = DB::table('people')
->join('blocks', 'people.user_id', '=', 'blocks.blocker')
->where('blocks.blocker', '<>', 'people.user_id')
->select('people.blog_id')
->get();
I think you should use right join here instead of simple join,
You can do it like.
$value = people::select(array('people.blog_id'))
->join('blocks', 'people.user_id', '=', 'blocks.blocker', 'right')
->where('people.user_id', $user->id)
->get()->toArray();
Please notice the fourth parameter in the join statement, this will include only the results where blocks will find.
Hope this will help

Prevent getting a duppicate data from the database in CodeIgniter

I'm trying to get data from the database filtered by some categories
This is my code in CodeIgniter
$this->db
->select('*')
->from($this->table)
->join('sites','sites.id = categories_by_site.site_id')
->where('categories_by_site.category_id', $categories[0])
->or_where('categories_by_site.category_id', $categories[1])
->order_by('id', 'ASC')
->get()
->result();
I simplify my code for the sake of this question, the above query take the categories as a search filter and used it to get result from the database.
There can be many categories filter to search at the same time, that's why I am using or_where() method.
The problem with this, when I got the result data, it has duplicate row of entries in object array.
Anyone can suggest how to prevent from getting a duppicate data from the database using above query?
Thanks
You can use group_by to solve this issue
Replace your code with
$this->db
->select('*')
->from($this->table)
->join('sites','sites.id = categories_by_site.site_id')
->where('categories_by_site.category_id', $categories[0])
->or_where('categories_by_site.category_id', $categories[1])
->order_by('id', 'ASC')
->group_by('categories_by_site.category_id')
->get()
->result();
You can eleminate duplicate values using distinct or group by
As you select all fields a group by is better in my opinion. Example to group by category_id
$this->db->group_by('category_id');

How can I retrieve the information I want using MySQL `joins` or Laravel `relationships`?

I am working on a project using the Laravel framework. In this project I have three tables:
1) Master Part Numbers (master_part_numbers)
Columns: id, part_number
Values: 1, MS26778-042
2) Inventory (inventory)
Columns: id, master_part_number, stock_qty
Values: 1, 1, 7
3) Inventory Min Maxes (inventory_min_maxes)
Columns: id, master_part_number, min_qty
Values: 1, 1, 10
I am trying to find the inventory where the stock level is below the min_qty. I have been attempting this using joins, like so:
$test = MasterPartNumber::table('master_part_numbers')
->join('inventory', 'master_part_numbers.id', '=', 'inventory.master_part_number_id')
->join('inventory_min_maxes', 'master_part_numbers.id', '=', 'inventory_min_maxes.master_part_number_id')
->select('master_part_numbers.part_number')
->where('inventory.stock_qty', '<=', 'inventory_min_maxes.min_qty')
->get();
However I am getting an empty collection every time. I have tried removing the where() clause and I get all the part numbers in the inventory, so it feels like I'm on the right track, but missing a critical component.
Also, I don't know if there is an easier or more efficient way to do this using Laravel's Eloquent Relationships, but that option is available.
Note: I added the space after table('master_part_numbers') in my query displayed here on purpose, for readability.
EDIT 1:
This sql query returns the expect result:
SELECT master_part_numbers.part_number
FROM master_part_numbers
JOIN inventory ON master_part_numbers.id=inventory.master_part_number_id
JOIN inventory_min_maxes ON master_part_numbers.id=inventory_min_maxes.master_part_number_id
WHERE inventory.stock_qty<=inventory_min_maxes.min_qty;
EDIT 2:
I finally got it working with some help from the Laravel IRC, however it isn't ideal because I am missing out on some of the data I would like to display, normally collected through relationships.
Here is what I am currently using, but I hope to get refactored:
DB::select(DB::raw('SELECT master_part_numbers.id, master_part_numbers.part_number, master_part_numbers.description, inventory.stock_qty, inventory.base_location_id, inventory_min_maxes.min_qty, inventory_min_maxes.max_qty
FROM master_part_numbers
JOIN inventory ON master_part_numbers.id = inventory.master_part_number_id
JOIN inventory_min_maxes ON master_part_numbers.id = inventory_min_maxes.master_part_number_id
WHERE inventory.stock_qty <= inventory_min_maxes.min_qty'));
If I have understood your problem correctly then
'masters_part_numbers.id' == 'inventory.id' and
'inventory.master_part_number' == 'inventory_min_maxes.master_part_number'
$test = DB::table('master_part_numbers')
->join('inventory', 'master_part_numbers.id', '=', 'inventory.id')
->join('inventory_min_maxes', 'inventory.master_part_number', '=', 'inventory_min_maxes.master_part_number')
->where('inventory.stock_qty', '<=', 'inventory_min_maxes.min_qty')
->whereNotNull('inventory_min_maxes.master_part_number');
->select(DB::raw('part_number'))
->get();
Based on above criteria. This code will work. I tried in laravel 5.4 .
Try and let me know. nd if it work give me a thumbs up
I discovered a way to solve this problem using the Laravel ->whereRAW() statement:
$test = $inventory->join('inventory_min_maxes', 'inventory.id', '=', 'inventory.inventory_min_max_id')
->whereRaw('inventory.stock_qty <= inventory_min_maxes.min_qty')
->whereRaw('inventory.inventory_min_max_id = inventory_min_maxes.id') // required so it tests against the specific record, without it will test against all records.
->get();
The major advantage for me, other than it looked terribly ugly before, was that I can now use the power of relationships.
Note: $inventory is an instance of my Inventory model, which I type hinted in the index() method.

Laravel 5.1 Eloquent whereBetween not working as expected

I have to get rows within a range of passed symbol no.
Image of Table from where query is to be done
Query:
Mark::select('users_id', 'symbol_no', 'mark_obtained')
->where('subject_trade_id', 2)
->whereBetween('symbol_no', [100, 1000])
->orderBy('symbol_no')
->get();
This query returns no data, but I was expecting total 9 rows form the query.
If I dump the query, I find the query as expected.
Query Log Image
If I run the generated query to mysql then it woks fine.
Again, if I change the symbol no. range to something like this:
Mark::select('users_id', 'symbol_no', 'mark_obtained')
->where('subject_trade_id', 2)
->whereBetween('symbol_no', [10, 1011])
->orderBy('symbol_no')
->get();
It returns 2 rows this time, and this output is also wrong.
If I try changing symbol no. range and query like this:
Mark::select('users_id', 'symbol_no', 'mark_obtained')
->where('subject_trade_id', 2)
->whereBetween('symbol_no', [101, 200])
->orderBy('symbol_no')
->get();
Now it works fine as expected.
Found the problem
By mistake the symbol_no column was defined as varchar() which had to be int() so, whereBetween() was being unable to return expected data.
I faced same problem.. Could you please check "symbol_no" field type in database table, It should be number/integer.

Categories