0

我正在尝试使用 Laravel 数据表库在表中加载模型数据。问题在于该表与自身存在关系,因此,当第一次加载数据时,一切正常,但如果我按具有关系的列排序,则会出现错误,因为在库生成的 sql 中它会尝试在同一个表之间进行连接,因此会给出错误“唯一表”。

我的数据表代码如下:

$dataTable = new EloquentDataTable($query);

    return $dataTable
    ->addColumn('dependents', function ($item) {
        return $item->dependents1->count() + $item->dependents2->count() + $item->dependents3->count();
    })
    ->filterColumn('leader.full_name', function($query, $keyword) {
        $sql = "exists(select * from `people` as `leader` where `leader`.`id` = `people`.`leader_id` and LOWER(`leader`.`full_name`) LIKE ? and `leader`.`deleted_at` is null)";
        $query->orWhereRaw($sql, ["%{$keyword}%"]);
    })
    ->filterColumn('leader2.full_name', function($query, $keyword) {
        $sql = "exists(select * from `people` as `leader2` where `leader2`.`id` = `people`.`leader2_id` and LOWER(`leader2`.`full_name`) LIKE ? and `leader2`.`deleted_at` is null)";
        $query->orWhereRaw($sql, ["%{$keyword}%"]);
    })
    ->filterColumn('leader3.full_name', function($query, $keyword) {
        $sql = "exists(select * from `people` as `leader3` where `leader3`.`id` = `people`.`leader3_id` and LOWER(`leader3`. `full_name`) LIKE ? and `leader3`.`deleted_at` is null)";
        $query->orWhereRaw($sql, ["%{$keyword}%"]);
    })
    ->orderColumn('leader.full_name', function ($query, $order) {
        /**it does not enter here, I don't understand why */
    })
    ->addColumn('action', 'people.datatables_actions')
    ->rawColumns(['photo', 'action']);

关系如下:

/**
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 **/
public function leader()
{
    return $this->belongsTo(\App\Models\Person::class, 'leader_id')->withDefault([
        'full_name' => ''
    ]);
}

/**
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 **/
public function leader2()
{
    return $this->belongsTo(\App\Models\Person::class, 'leader2_id')->withDefault([
        'full_name' => ''
    ]);
}

/**
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 **/
public function leader3()
{
    return $this->belongsTo(\App\Models\Person::class, 'leader3_id')->withDefault([
        'full_name' => ''
    ]);
}

如果你能看到,我尝试使用 orderColum 函数,但它不适用于前景字段。

谢谢你能给我的帮助

4

0 回答 0