事情是这样的,有天写了一个左连接查询,由于表名太长,所以分别给起个别名,代码如下
事情是这样的,有天写了一个左连接查询,由于表名太长,所以分别给起个别名,代码如下:
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 点了,下班。
以上这篇Laravel 模型使用软删除-左连接查询-表起别名示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
Laravel 软删除 左连接 查询