Laravel 模型使用軟刪除-左連線查詢-表起別名

iyoungm發表於2018-08-27

事情是這樣的,有天寫了一個左連線查詢,由於表名太長,所以分別給起個別名,程式碼如下:

public function detail()
{
    $result = TakeOrderModel::query()
        ->from('take_order as order')
        ->leftJoin('take_order_detail as detail', 'order.id', '=', 'detail.take_order_id')
        ->get();
    dd($result);
}

執行後,報錯 Column not found: 1054 Unknown column take_order.delete_time

檢視解決辦法的,直接看底部

SQL:

select * from take_order as order
left join take_order_detail as detail
on order.take_order_id = detail.take_order_id
where take_order.delete_time is null

顯而易見:軟刪除查詢條件的表名是全名,所以報錯了。

分析

軟刪除作用域 SoftDeletingScope 原始碼:

/**
 * Apply the scope to a given Eloquent query builder.
 *
 * @param  \Illuminate\Database\Eloquent\Builder  $builder
 * @param  \Illuminate\Database\Eloquent\Model  $model
 * @return void
 */
public function apply(Builder $builder, Model $model)
{
    $builder->whereNull($model->getQualifiedDeletedAtColumn());
}

檢視 getQualifiedDeletedAtColumn 原始碼:

/**
 * Get the fully qualified "deleted at" column.
 *
 * @return string
 */
public function getQualifiedDeletedAtColumn()
{
    return $this->qualifyColumn($this->getDeletedAtColumn());
}

檢視 qualifyColumn 原始碼:

/**
 * Qualify the given column name by the model's table.
 *
 * @param  string  $column
 * @return string
 */
public function qualifyColumn($column)
{
    return $this->model->qualifyColumn($column);
}

檢視 qualifyColumn 原始碼:

/**
 * Qualify the given column name by the model's table.
 *
 * @param  string  $column
 * @return string
 */
public function qualifyColumn($column)
{
    if (Str::contains($column, '.')) {
        return $column;
    }

    return $this->getTable().'.'.$column;
}

以上可知: $this->getTable().'.'.$column 即為軟刪除條件的欄位名。

解決辦法

程式碼改成下面這樣,加一行 setTable 設定表名,就可以了。

$result = (new TakeOrderModel())
        ->setTable('order')
        ->from('take_order as order')
        ->leftJoin('take_order_detail as detail', 'order.take_order_id', '=', 'detail.take_order_id')
        ->get();

因為寫程式碼時要指定具體的查詢 columns ,有時表名真的太長,看著很不舒服,所以有此嘗試。嗯,9 點了,下班。

相關文章