php - Laravel - Filtering a Model by Condition between "a Field and Its Relationship Model Field"
Get the solution ↓↓↓I have these two models with one to one relationship.
"products"
- id
- name
- minimum_required
"product_data"
- id
- product_id
- price
- oh_hand
I want to get the count of product_data where its on_hand is less than its related product's minimum_required.
I've tried subqueries and I still can't figure it out. The query I want may looks something like this.
$low_products_count = ProductDetail::where('on_hand', '<', Product::select('minimum_required')->count();
Answer
Solution:
you can join the tables then use 'whereColumn':
$low_products_count =Product::join('product_data','product_data.product_id','=',
'products.id')->whereColumn('product_data.on_hand','<','products.minimum_required')->get();
Answer
Solution:
I am not experienced with the eloquent So here, I share my knowledge with the query builder.
You can do like this->
$low_products_count=DB::table('products')
->join('product_data','product_data.product_id','=',
'product.id')
->where('product_data.on_hand','<','products.minimum_required')->get();
You can use this concept.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: integrity constraint violation: 1452 cannot add or update a child row: a foreign key constraint fails
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.