Reputation: 7076
My query is like this :
SELECT * FROM message WHERE (seller_id = 1 OR buyer_id = 3) AND deleted_by NOT LIKE '%1%'
I want change it to laravel eloquent
I try like this :
Message::where('seller_id', auth()->user()->id)
->orWhere('buyer_id', auth()->user()->id)
->where('deleted_by', 'not like', '%'.auth()->user()->id.'%')
->get();
But, the result like this :
SELECT * FROM message WHERE seller_id = 1 OR buyer_id = 3 AND deleted_by NOT LIKE '%1%'
Seems it need brackets
How can I add brackets on the laravel eloquent?
Upvotes: 10
Views: 7408
Reputation: 2044
In such cases, use closure.
$userId = auth()->user()->id;
Message::where(function($q) use($userId){
$q->where('buyer_id', $userId)
->orWhere('buyer_id', $userId);
})
->where('deleted_by', 'not like', '%'.$userId.'%')
->get();
Upvotes: 7
Reputation: 1465
Message::where(function ($query) {
$query->where('seller_id', auth()->user()->id)
->orWhere('buyer_id', auth()->user()->id);
})
->where('deleted_by', 'not like', '%'.auth()->user()->id.'%')
->get();
Try this, may be your problem get resolved.
Upvotes: 4
Reputation: 13259
You need to put your where in a closure
Message::where(function($query){
$query->where('buyer_id', auth()->user()->id)
->orWhere('buyer_id', auth()->user()->id);
})
->where('deleted_by', 'not like', '%'.auth()->user()->id.'%')
->get();
Upvotes: 20
Reputation: 1541
Try this :
Message::where(function ($query) {
$query->where('seller_id', auth()->user()->id)
->orWhere('buyer_id', auth()->user()->id);
})->where('deleted_by', 'not like', '%'.auth()->user()->id.'%')->get();
Upvotes: 3