问题描述
我想通过存储在单独表(在此示例中为tapp)中的某些特征来过滤项目(在这种情况下为pubs),并且两者都与pub_tapps相关.
I would like to filter an item (pubs, in this case) by some characteristics that are stored in a separate table (tapps, in this case), and both are related by pub_tapps.
我有以下表格:酒吧,小吃,pub_tapps(pub_id,tapp_id)
I have the following tables: pubs, tapps, pub_tapps(pub_id, tapp_id)
Pub和Tapp之间的关系如下:
The relation between Pub and Tapp is the following:
public function pubTapps()
{
return $this->belongsToMany(Tapp::class, 'pub_tapps');
}
在我的Pub模型中,我尝试对数组$ request = [5,8,7]进行以下测试:
in my Pub model I tried the following testing for an array $request=[5,8, 7]:
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();
}
这很好,但是对于给定的3维数组...
This is working perfectly, but for a given 3 dimensional array...
如何处理长度为n的数组?
How can I do for an array of an n length??
我尝试了这个,但是根本不起作用(返回一个空数组):
I tried this, but doesn't work at all (returns an empty array):
return $pubs = Pub::whereHas('pubTapps', function ($query) use
($tapps_chosen) {
foreach ($tapps_chosen as $tappId) {
$query->where('tapp_id', $tappId);
}
})->get();
我该怎么办???任何使它起作用的想法?
What would I have to do??? Any ideas to make it work??
非常感谢!
推荐答案
使用此:
$query = Pub::query();
foreach ($tapps_chosen as $tappId) {
$query->whereHas('pubTapps', function($query) use($tappId) {
$query->where('tapp_id', $tappId);
});
}
return $query->get();
这篇关于查询关系存在,如何根据数组长度添加条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!