Home > Net >  Laravel orWhereRaw with join
Laravel orWhereRaw with join

Time:08-11

I'm trying to get the below query working. The latest error I'm getting is Object of class Closure could not be converted to string.

I was reading that in older versions of Laravel (5.2), that: $query is instance of JoinClause and it does not have whereRaw() methods.(https://stackoverflow.com/a/47672758/4113027)

How can I write this query such that it works?

$results = DB::table('statement_transactions AS st')
            ->join('quickbooks_transactions AS qt', function ($join) {
                $join->on('st.transaction_date', '=', 'qt.transaction_date');
                $join->on('st.transaction_type_id', '=', 'qt.transaction_type_id');
                $join->on('st.original_amount', '=', 'qt.original_amount');
                $join->on('st.balance', '=', 'qt.balance');
            })
            ->where('st.statement_id', $this->statement->id)
            ->where('st.has_match', 0)
            ->where('st.has_partial_match', 0)
            ->whereNull('st.quickbooks_transaction_id')
            ->orWhereRaw(function ($query) {
                $query->whereRaw("LEFT(REPLACE(st.invoice_nbr, '-', ''), 5) = LEFT(REPLACE(qt.invoice_nbr, '-', ''), 5)")
                    ->whereRaw("RIGHT(REPLACE(st.invoice_nbr, '-', ''), 5) = RIGHT(REPLACE(qt.invoice_nbr, '-', ''), 5)");
            })
            ->select('st.id AS statement_transaction_id', 'qt.id AS quickbooks_transaction_id')
            ->get();

CodePudding user response:

The issue is here:

->orWhereRaw(function ($query) {
    $query->whereRaw("LEFT(REPLACE(st.invoice_nbr, '-', ''), 5) = LEFT(REPLACE(qt.invoice_nbr, '-', ''), 5)")
    ->whereRaw("RIGHT(REPLACE(st.invoice_nbr, '-', ''), 5) = RIGHT(REPLACE(qt.invoice_nbr, '-', ''), 5)");
})

orWhereRaw() expects one argument, a string. Instead, you're passing it a closure (i.e. your function ($query) { ... }).

You need to change orWhereRaw to orWhere, which does accept a closure.

  • Related