Laravel 模型使用软删除-左连接查询-表起别名示例
程序员文章站
2022-06-22 10:25:02
事情是这样的,有天写了一个左连接查询,由于表名太长,所以分别给起个别名,代码如下:
public function detail()
{
$result = take...
事情是这样的,有天写了一个左连接查询,由于表名太长,所以分别给起个别名,代码如下:
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 模型使用软删除-左连接查询-表起别名示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。