在laravel ORM

时间:2015-12-28 13:18:05

标签: php mysql laravel eloquent laravel-orm

控制器:

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

型号:

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");
      }
}

表格结构:

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 

问题:

  

SQLSTATE [42S22]:未找到列:1054未知列' w1.id'在' on条款'

我尝试过给别名,但它已经显示了error

希望有人能为此解决问题...... !!

1 个答案:

答案 0 :(得分:1)

我得到了解决方案,

// 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');
}

我只需要使用DB::raw(),这对我有帮助......