FastAdmin后台关联查询报错表不存在

FastAdmin后台在使用关联查询时,报错表不存在,SQLSTATE[42S02]: Base table or view not found: 1146 Table 'fastadmin.user' doesn't exist

问题背景:

  1. 后台User控制器的index方法在查询时关联了user表(前缀是fa_),定义如下
// User model
public function puser(){
    return $this->belongsTo('\app\admin\model\User', 'pid','id', [], 'LEFT')->setEagerlyType(0);
}

// User index
$total = $this->model ->with(['puser'])->where($where)->order($sort, $order)->count();

其中pid是用户的上一级。

  1. 搜索条件为空时,一切正常;
  2. 当按表里的添加时间字段搜索时,报错:SQLSTATE[42S02]: Base table or view not found: 1146 Table 'fastadmin.user' doesn't exist
  3. 关联其它表没这个问题,就关联同名的表报这个错误。

解决办法有点复杂,相当于区线救国:

  1. list($where, $sort, $order, $offset, $limit) = $this->buildparams();后面,先构造不含关联查询的SQL语句
$sql = $this->model->where($where)->buildSql();
$where_index = stripos($sql, 'WHERE');
if($where_index){
   $sql_where = substr($sql, $where_index);
   $sql_where = substr($sql_where, 0, -1);
}else{
   $sql_where = "";
}
  1. 手写SQL语句,把上面的where条件拼上去。注意的是需要构造两条,一条查总条数,一条查列表,列表那条需要把order bylimit也手动拼上去。

问题解决!

Leave a Comment

豫ICP备19001387号-1