I have a bit complex query that I need help with:
Logic
- Table
subscriptions
have rows withuser_id
(each user can have many rows) - Table
products
requiretokens
(example 2 tokens is required for product A) - Now this tokens has to be calculated based on user subscription amount. Let say user has 2 rows in subscriptions table, one with
1
token and other one with5
tokens (user have 6 tokens in total) and he need to use2
of them only. - What I’m trying to do here is to update subscriptions table for this user and mark his rows
used_tokens
column by incrementing them.
You might be confused a bit now! here is screenshots to make it
visually understandable for you.
products table
subscriptions table
Issue
Issue is I cannot make it happen to update used_tokens
columns in this two rows in subscriptions
table.
Here is what it should look like at the end
Code
This is what I have so far (getting right product, getting user subscriptions) and I need to update those subscriptions:
$product = Product::findOrFail($request->input('product_id')); // Get product
$required_tokens = $product->required_tokens; // Get product require tokens (i.e. 2)
$subscriptions = Subscription::where('user_id', $user->id)->where('isPaid', true)->where('used_tokens', '<', 'tokens')->get(); // Get user subscription rows
How can I update (increment) used_tokens
in those rows?
2
Answers
How about something like that?
Final (cleaned up) code
You can update multiple models at once in laravel using laravel eloquent relationships
After setting this relationship, you can update the user’s subscriptions using the code below: