Here's my Database Structure:
Products : ['id','name','image']
Request : ['id','marketer_id','distributor_id']
RequestItems : ['id','request_id','product_id','quantity']
Now this is just a short example of structure. what I'm trying to do is that, I have a page with request, which in this page I'm getting items in a request base on RequestItems
table, and i want to add a button in my page to add product to this request, but i want to show products that are not exist in RequestItems
.
I can make a condition to check before adding product to make sure user won't add 1 product 2 times in a request, but i also want to make it clear that user see products in add button which it's already exist in his request items.
I just need help for Query, I'm developing with Laravel
& vue.js
for SPA.
My Solution (But looking for better Solution) :
public function getRequestRepresentativeSideProducts(RepresentativesRequests $id, Request $request){
$products = DistributorProducts::where(
'distributor_id', $request->distributor_id
)
->latest()
->get();
$data = $id->items()->latest()->get();
$myArray = array();
for ($i = 0; $i < $data->count(); $i++)
{
$myArray[] = $data[$i]->product_id;
}
return $products->except($myArray);
}
Edit 01 : I've managed to get response with below query, but It's taking all data
$data = DistributorProducts::doesntHave('requestRepresentativeSideItems', 'and', function ($query){
$query->where('representative_request_id', '=', 1);
})->where('distributor_id', $request->distributor_id)
->latest()
->get();
$data = DistributorProducts::whereDoesntHave('requestRepresentativeSideItems', function (Builder $query) use ($id) {
$query->where('representative_request_id', 'like', $id->id);
})->where('distributor_id', $request->distributor_id)
->latest()
->get();
$data = DistributorProducts::whereDoesntHave('requestRepresentativeSideItems', function (Builder $query) use ($id) {
$query->where('representative_request_id', $id->id);
})->where('distributor_id', $request->distributor_id)
->latest()
->get();
I have 3 products for distributor_id
which 2 of them are in request items, so my query should show 1 but will above query still I'm getting all products.
Edit 02: I've checked where from $query and used like too and changed request_id but didn't changed result at all. looks like it's just ignoring that part.