Donnie
Donnie

Reputation: 6341

Eloquent: Incorrect column in join statement

I’m attempting to join the perspectives table to the offers table based partly on the authenticated organization id. However, Eloquent keeps trying to join on a column name of "2" rather than a value of 2. This seems to be primarily an issue of context.

What, pray tell, is the solution?

Ye Olde Scope

public function scopeReceived($query)
{
  return $query
    ->where('recipient_id', Auth::user()->organization_id)
    ->join('perspectives', function ($join) {
      $join
        ->on('perspectives.organization_id', '=', Auth::user()->organization_id)
        ->on('perspectives.offer_id', '=', 'offers.id');
    });
}

Ye Olde Error

  SQLSTATE[42S22]: Column not found: 1054 Unknown column '2' in 'on clause',

Ye Olde Query Statement

SELECT * FROM `offers`
INNER JOIN `perspectives`
    ON `perspectives`.`organization_id` = `2`
    AND `perspectives`.`offer_id` = `offers`.`id`

Upvotes: 0

Views: 146

Answers (1)

Ersoy
Ersoy

Reputation: 9586

Surrounding the third parameter(constant) on your join-on clause with DB::raw() could solve the problem.

->on('perspectives.organization_id', '=', DB::raw(Auth::user()->organization_id))

Upvotes: 1

Related Questions