根据子表中的“当前”值过滤belongsToMany 记录

时间:2021-07-23 13:22:52

标签: laravel eloquent yajra-datatable

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

单位

  • id
  • ...

所有权

  • id
  • contact_id
  • unit_id
  • date_from
  • 日期到

联系方式

  • id
  • ...

我的目标是能够按当前所有者的姓名过滤单元。每个单元都有多个分配给它的所有者,它们具有开始日期 (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'),
    ];
}

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

1 个答案:

答案 0 :(得分:0)

   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'),
    ];
}