【问题标题】:Filtering belongsToMany records based on "current" value from child table根据子表中的“当前”值过滤 belongsToMany 记录
【发布时间】:2021-09-30 14:59:09
【问题描述】:

我正在使用yajra/laravel-datatables 构建一个 Laravel 应用程序,我在其中尝试过滤多对多关系中的记录。我有 3 个模型参与其中 - 单位、所有权、联系人:

单位

  • 身份证
  • ...

所有权

  • 身份证
  • contact_id
  • unit_id
  • date_from
  • date_to

联系方式

  • 身份证
  • ...

我的目标是能够按当前所有者的名称过滤单元。每个单元都有分配给它的多个所有者,它们具有开始日期 (date_from) 和结束日期 (date_to)。

单元模型

public function ownerships() {
    return $this->hasMany(Ownership::class);
}

// I also tried something like this
// Datatable ignores it though and fetches all ownerships
public function current_ownership() {
    return $this->hasOne(Ownership::class)->latest('date_from')->limit(1);
}

所有权模式

public function contact() {
    return $this->belongsTo(Contact::class);
}

public function unit() {
    return $this->belongsTo(Unit::class);
}

我也尝试过像这样在我的单元模型上使用 belongsToMany。然而,这也没有让我有所收获。

public function owners() {
    return $this->belongsToMany(Contact::class, 'ownerships', 'unit_id', 'contact_id')
        ->using(Ownership::class)
        ->withPivot('date_from', 'date_to');
}

现在我的UnitDataTable数据表设置如下。

public function query(Unit $model) {
    return $model->with([
        'ownerships.contact',
        'tenancies.contact',
    ])
    ->select('units.*')
    ->where('house_id', $this->house_id)
    ->newQuery();
}

// Excerpt of actual full getColumns()
protected function getColumns() {
    return [
        Column::make('ownerships')
            ->name('ownerships.contact.last_name')
            ->title('Owner'),
    ];
}

到目前为止,数据表可以正常工作。但是,搜索名称也会返回不再是所有者但存在于单元所有者历史中的名称。我似乎无法弄清楚,如何将我的姓名搜索限制为最新/当前所有者。

【问题讨论】:

    标签: laravel eloquent yajra-datatable


    【解决方案1】:
       public function query(Unit $model)
    {
    return $model->with([
            'ownerships.contact',
            'tenancies.contact',
        ])
        ->filterColumn('ownerships', function ($query, $keyword) {
           $query->whereHas('ownerships.contact', function ($q) use ($keyword) {
              $q->where('last_name', 'LIKE', "%{$keyword}%");
          });
        })
        ->select('units.*')
        ->where('house_id', $this->house_id)
        ->newQuery();
    }
    
    // Excerpt of actual full getColumns()
    protected function getColumns()
    {
        return [
            Column::make('ownerships')
                  ->name('ownerships.contact.last_name')
                  ->title('Owner'),
        ];
    }
    

    【讨论】:

    • 你试过了吗?它看起来对我不起作用,因为 filterColumn 是 yajra/laravel-datatables 的一种方法,因此在 Eloquent\Builder 中不可用。我试过了,结果是“调用未定义的方法”
    猜你喜欢
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 2020-03-17
    • 1970-01-01
    • 2021-06-07
    • 2010-10-28
    相关资源
    最近更新 更多