Ok so I tried whith your answers, I can return Invoices associated to a user but i cant get the products inside this invoice, I want to get the Invoice associated to the user with his products only.
If i mention the id of the user who creates a product and the id of the invoice, i want the query to return me the invoice with the products associated to the id of the user mentionned.
when Iam using this :
$Invoices = Commande::find(1)->whereHas('Product', function($query){
return $query->where('products.user_id', 3);
})->with('Product')->get();
I get only the Invoices.
But i want the Invoice and the products in this invoice that are associated to a certain user.
CodePudding user response:
That's where the whereHas()
method comes into place. You should be able to do something like this:
$user = User::find($userId); // Let's assume `$userId` is `1`
$invoices = Invoice::whereHas('products', function ($query) use ($user) {
return $query->where('products.user_id', $user->id);
})->get();
That will return all Invoice
records that are associated with the $user
record returned by User::find($userId)
(again, in this case, user_id: 1
)
You can see the full documentation here:
https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence
Note: You might need to adjust the model/relationship names I used in the code above to fit your needs, but the basic idea remains the same.
CodePudding user response:
You can use this query to get invoices and their products belonging to a specific user
// my user id is currently authenticated, user
Invoice::query()->where('user_id', auth()->user()->id)->with('products')->paginate();