php – Laravel eloquent join multiple tables in the leftjoin-ThrowExceptions

Exception or error:

I’m new in laravel. I’m trying to join multiple tables in the left join however i facing the syntax error and i have no idea where goes wrong.


$query = DB::table('sales')
    ->leftjoin('transactions AS trx', function ($join) {
        $join->on('payment_methods AS payment', '', '=', 'trx.payment_method_id');
        $join->on('transactables', 'transactables.transaction_id', '=', '')
            ->where('transactable_type', '=', 'Sale')
            ->where('transactable_id', '=', '');

The error meesage

Syntax error near '`payment_methods` as `payment` `=` and `transactions`.`deleted_at` is'

As the code above you can see. I’m trying to join table payment_methods and transactables within the transactions table.

How to solve:

Why don’t you use the Eloquent like

$sales = Sale::with('transactions')->get();

Add relation in Sale model

public function transactions()
    return $this->morphToMany('App\Transaction', 'transactable');

For more info, please refer to Laravel docs

Leave a Reply

Your email address will not be published. Required fields are marked *