我想通过存储在单独的表中的某些特性(在本例中为tapps)过滤项(pubs,在本例中),并且两者都与pub_tapps相关。
我有以下表格:pubs,tapps,pub_tapps(pub_id,tapp_id)
Pub和Tapp之间的关系如下:
compile
在我的Pub模型中,我尝试了以下测试数组$ request = [5,8,7]:
public function pubTapps()
{
return $this->belongsToMany(Tapp::class, 'pub_tapps');
}
这是完美的,但对于给定的三维数组...
如何处理n长度的数组?
我尝试了这个,但根本不起作用(返回一个空数组):
public function pubsFilteredByTapps(FilteredTappsPubsRequest $request)
{
$tapps_chosen = $request->get('tapps');
$tapps_chosen = is_string($tapps_chosen) ? explode(',', str_replace('"', '', $tapps_chosen)) : $tapps_chosen;
return Pub::whereHas('pubTapps', function($query) use($tapps_chosen) {
$query->where('tapp_id', $tapps_chosen[0]);
})
->whereHas('pubTapps', function($query) use($tapps_chosen) {
$query->where('tapp_id', $tapps_chosen[1]);
})
->whereHas('pubTapps', function($query) use($tapps_chosen) {
$query->where('tapp_id', $tapps_chosen[2]);
})
->get();
}
我该怎么办?任何让它发挥作用的想法??
非常感谢!
答案 0 :(得分:1)
使用此:
$query = Pub::query();
foreach ($tapps_chosen as $tappId) {
$query->whereHas('pubTapps', function($query) use($tappId) {
$query->where('tapp_id', $tappId);
});
}
return $query->get();
答案 1 :(得分:0)
这个怎么样?
public function pubsFilteredByTapps(FilteredTappsPubsRequest $request)
{
$tapps_chosen = $request->get('tapps');
$tapps_chosen = is_string($tapps_chosen) ? explode(',', str_replace('"', '', $tapps_chosen)) : $tapps_chosen;
return Pub::whereHas('pubTapps', function($query) use($tapps_chosen) {
$query->whereIn('tapp_id', explode(',' $tapps_chosen));
})->get();
}
这样,如果数组中有任意数量的ID,eloquent将生成带有IN子句的请求,您将获得正确的结果。