【发布时间】: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