Reputation: 2191
My Query:
Payment::whereHas('subscription',function($q)
{
$q->where('ends_at','>',today());
})->orWhereDoesntHave('subscription')->where('user_id',1)->first();
Output:
App\Payment {#4339
id: 6,
user_id: 317,
package_id: 6,
amount: 12500,
phone: "01849744603",
transaction_id: "F1234",
confirmed: 1,
created_at: "2020-11-29 14:29:08",
updated_at: "2020-11-29 16:40:03",
}
My logic is: when I make a payment, a subscription is created for a specific package for a certain duration if an admin approves the payment. I want to get the payment information of a user if he is not subscribed but made payment or his subscription has not expired. I wrote the above code that gives me an output for the first payment information of the database. Not for the user of the given user_id
in the query. How should I approach? And what is the problem here? Can anyone help me?
Upvotes: 3
Views: 3437
Reputation: 18916
The problem is probably about precedence in the logical operators in SQL. Your generated SQL would be pseudo something like this.
in (select * from subscriptions) OR ! in (select * from subscriptions) and user_id = 1
Wrapping your query in a where()
with a closure would create parenthesis in the SQL around the first part and secure precedence is correct.
Payment::where(function ($query) {
$query->whereHas('subscription', function($q)
{
$q->where('ends_at','>',today());
})->orWhereDoesntHave('subscription');
})->where('user_id',1)->first();
Upvotes: 6