事情是这样的,有天写了一个左连接查询,由于表名太长,所以分别给起个别名,代码如下:
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 点了,下班。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
长按识别二维码并关注微信
更方便到期提醒、手机管理