【问题标题】:Searching an accessor of eager-loaded relation from datatables从数据表中搜索预加载关系的访问器
【发布时间】:2018-11-20 17:18:28
【问题描述】:

我有以下型号:

<?php
class User extends Model {
    public function department() {
        return $this->hasOne(Department::class);
    }
}

class Department extends Model {
    protected $appends = ["email"];
    public function getEmailAttribute() {
        return "$this->name@$this->domain";
    }
    public function user() {
        return $this->belongsTo(User::class);
    }
}

我正在提取用户列表,包括他们的部门,并在带有服务器端分页/排序/搜索的数据表中显示(使用 Laravel DataTables 包):

<?php
class UserController extends Controller {
    public function dt() {
        $users = User::with("department")
            ->where("location_id", session("current_location"));
        return DataTables::of($users)->make();
    }
}

在数据表设置中,我的一列定义如下:

{data: "department.email"}

这将毫无问题地显示email 访问器属性。当我尝试根据此列进行搜索或排序时出现问题:

DataTables 警告:表 id=DataTables_Table_0 - 异常消息:

SQLSTATE[42S22]:找不到列:1054 'where 子句'中的未知列'departments.email'

显然,datatables 不知道这是一个访问器,并尝试将其包含在查询中——结果可预测。

我能找到参考的唯一解决方法是使用the filterColumn method,它允许您为特定列定义自定义WHERE 子句。但据我所知,a) 要求您使用查询构建器手动定义列,而 b) 仅适用于模型,而不是其中的一个关系。

有什么方法可以像使用关系的“真实”属性一样搜索和排序此访问器属性?

【问题讨论】:

  • 您找到解决方案了吗?遇到同样的问题。我没有使用关系,但仍然无法搜索访问器字段。
  • @waterloomatt 是的,在我提出这个问题大约一年后,我确实让它工作了。请参阅下面的答案。

标签: php laravel yajra-datatable laravel-datatables


【解决方案1】:

这就是我最终解决这个问题的方法。这不是一个理想的解决方案,但基本上我在 SQL 中重新创建了访问器,手动构建查询,然后使用 Datatables 的filterColumn 功能。

<?php
class UserController extends Controller {
    public function dt() {
        $concat = "CONCAT(departments.name, '@', departments.domain)";

        $users = User::select(["users.*", DB::raw("$concat AS dept_email")])
            ->leftJoin("departments", "users.department_id", "=", "departments.id")
            ->whereNull("departments.deleted_at")
            ->where("location_id", session("current_location"))
            ->with("departments");

        return DataTables::of($users)
            ->filterColumn(
                "dept_email",
                fn ($q, $k) => $q->whereRaw("$concat LIKE ?", ["%$k%"]);
            )
            ->make();
    }
}

然后我将生成的列包含在我的表定义中,搜索按预期工作。

【讨论】:

    【解决方案2】:

    尝试将访问器附加到模型。

    class Department extends Model {
    
        protected $appends = ['email'];
    
        // the rest of your code
    }
    

    注意:appends 数组中的属性也将遵循模型上配置的 visiblehidden 设置。

    来源:Appending Values To JSON

    【讨论】:

    • 已经附加了;正如我所说,这封电子邮件显示得很好——只是因为 Laravel Datatables 的处理方式而无法搜索。
    猜你喜欢
    • 2014-07-02
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 2017-12-13
    • 2020-05-14
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    相关资源
    最近更新 更多