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

Posted

技术标签:

【中文标题】根据子表中的“当前”值过滤 belongsToMany 记录【英文标题】:Filtering belongsToMany records based on "current" value from child table 【发布时间】: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'),
    ];

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

【问题讨论】:

【参考方案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 中不可用。我试过了,结果是“调用未定义的方法”

以上是关于根据子表中的“当前”值过滤 belongsToMany 记录的主要内容,如果未能解决你的问题,请参考以下文章

根据子表的条件修改主表的数据

如何编写一个查询,根据 ms 访问的子表中的外键获取信息?

根据另一个表中的自定义属性过滤值

如何根据另一个表中的 %LIKE% 值过滤表

SQLAlchemy 根据另一个表中的值过滤表的最佳方法

使用另一个表laravel中的当前值插入数据?