Read the docs here. https://laravel.com/docs/12.x/queries#logical-grouping
How do I do this db query with eloquent?
Hi friends,
I have a case where I need to have a special "WHERE" clause that include a some criteria to be ORed then the result be ANDed with other criteria. I'm not able to achieve this by chaining where() and orWhere() methods. The query should look like this:
SELECT bank_transactions.*, journal_entries.bank_transaction_id, journal_entries.description FROM bank_transactions, journal_entries WHERE bank_account_id=x AND journal_entries.bank_transaction_id = bank_transactions.id AND ( bank_transactions.description like '%something%' OR bank_transactions.payee_name like '%something%' OR journal_entries.description like '%something%' );
I'm not interested in joining two tables above as each record in bank_transactions table is related to two records in journal_entries tables (hasMany).
How can I do this in eloquent way?
Thanks in advance.
@r9host you need to typehint the correct Builder class; which you can alias like this
use Illuminate\Database\Query\Builder;
DB::table('bank_transactions')
->where('bank_account_id', 1)
->where(function(Builder $query) {
$query->where('description', 'like', '%something%')
->orWhere('payee_name', 'like', '%something%');
});
Or, you can just omit the typehint, and it'll still work for you
DB::table('bank_transactions')
->where('bank_account_id', 1)
->where(function($query) {
$query->where('description', 'like', '%something%')
->orWhere('payee_name', 'like', '%something%');
});
There is also a very useful whereAny method which might be easier to use here (it will take care of logical grouping automatically:
use Illuminate\Database\Query\Builder;
DB::table('bank_transactions')
->where('bank_account_id', 1)
->whereAny(['description', 'payee_name'], 'like', '%something%')
->get();
Please or to participate in this conversation.