Ad

Two Left Join With Same Table With Addselect() In Laravel ORM

- 1 answer

Controller:

$warehouse_transfer = WarehouseTransfer::mySelect(array('date', 'from_warehouse_id', 'to_warehouse_id'))
            ->where('warehouse_transfer.id', $id)
            ->first();

Model:

public function scopeMySelect($q, $columns = array()) {
    $q->addSelect("warehouse_transfer.id")
    // date
    if (in_array('date', $columns)) {
        $q->addSelect(DB::raw("DATE_FORMAT(oops_warehouse_transfer.date, '%d-%m-%Y') as date"));
    }

    // Warehouse Transfer From
    if (in_array('from_warehouse_id', $columns)) {
        $q->addSelect("warehouse_transfer.from_warehouse_id");
        $q->addSelect('warehouse_transfer.from_warehouse_id', 'w1.name AS from_warehouse_name');
        ->leftJoin('warehouse As w1', 'w1.id', '=', 'warehouse_transfer.from_warehouse_id');
    }
    // Warehouse Transfer To
    if (in_array('to_warehouse_id', $columns)) {
        $q->addSelect("warehouse_transfer.to_warehouse_id");
        $q->addSelect('warehouse_transfer.to_warehouse_id', 'w2.name AS to_warehouse_name');
        ->leftJoin('warehouse AS w2', 'warehouse_transfer.to_warehouse_id', '=', 'w2.id');
     }
     // Warehouse Transfer Staff Name
     if (in_array('staff_name', $columns)) {
         $q->addSelect("staff.name as staff_name")
                ->leftjoin('staff', 'staff.id', '=', 'warehouse_transfer.staff_id');
      }

      // Warehouse Transfer ITP
      if (in_array('itp', $columns)) {
          $q->addSelect("warehouse_transfer.itp");
      }

      // Warehouse Transfer UTP
      if (in_array('utp', $columns)) {
          $q->addSelect("warehouse_transfer.utp");
      }
}

Table Structure:

warehouse:

1   id
2   name
3   code
4   status
5   itp
6   utp 

warehouse_transfer:

1   id
2   date
3   from_warehouse_id
4   to_warehouse_id
5   staff_id
6   itp
7   utp 

Problem:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'w1.id' in 'on clause'

I have tried by giving alias but it's gives error that have shown

Hope someone have solution for this...!!

Ad

Answer

I get the Solution,

// Warehouse Transfer From
if (in_array('from_warehouse_id', $columns)) {
    $q->addSelect(DB::raw("fromw.id as from_warehouse_id, fromw.name from_warehouse_name"))
    ->leftjoin(DB::raw('oops_warehouse AS fromw'), DB::raw('fromw.id'), '=', 'warehouse_transfer.from_warehouse_id');
}

// Warehouse Transfer To
if (in_array('to_warehouse_id', $columns)) {
    //$q->addSelect('warehouse_transfer.to_warehouse_id', 'warehouse.name AS to_warehouse_name');
    $q->addSelect(DB::raw("tow.id as to_warehouse_id, tow.name to_warehouse_name"))
    ->leftjoin(DB::raw('oops_warehouse AS tow'), DB::raw('tow.id'), '=', 'warehouse_transfer.to_warehouse_id');
}

Just i required to use DB::raw() and it does the trick for me...

Ad
source: stackoverflow.com
Ad