【发布时间】:2021-11-14 04:06:26
【问题描述】:
所以,我已经设法彻底混淆了自己,任何帮助将不胜感激。 我想要做的是过滤掉受用户国家限制的项目(在我的控制器中完成)。
我的第一个查询获取所有项目(在这种情况下为海报)。我的第二个项目得到了限制海报。此代码按计划运行。
然后,我尝试创建一个嵌套循环,通过创建一个新数组并将传递我的 if 子句的项目推入我的 $unrestrictedPosters 数组来从所有海报中过滤出受限海报。我的 if 子句是我的代码失败的地方,因为我无法正确访问键值以实现我的 if 子句。
顺便说一句,一旦我返回 $unrestrictedPosters 之后,它将在我的 bade 文件中使用和循环。
控制器代码如下
class PosterRestrictionController extends Controller
{
public function index()
{
$profile = app('App\Http\Controllers\DevelopmentController')->getActiveUser(Auth::id());
$userCountry = $profile->country;
$unrestrictedPosters = [];
$allPosters = DB::table('posters')
->join('profiles', 'posters.user_id', '=', 'profiles.user_id')
->join('users', 'posters.user_id', '=', 'users.id')
->select('users.name',
'profiles.surname',
'profiles.country',
'posters.id as poster_id',
'posters.user_id',
'posters.title',
'posters.category',
)
->orderBy('posters.id', 'asc')
->get();
$restrictedPosters = DB::table('posters')
->join('poster_restrictions', 'poster_restrictions.poster_id', '=', 'posters.id')
->where('poster_restrictions.restricted_country_id', '=', $userCountry)
->select(
'posters.id as poster_id',
'poster_restrictions.poster_viewable',
'poster_restrictions.restricted_country_id'
)
->orderBy('posters.id', 'asc')
->get();
foreach ($allPosters as $poster) {
foreach ($restrictedPosters as $restrictedPoster) {
if ($restrictedPoster['poster_viewable'] != 0) {
array_push($unrestrictedPosters, $poster);
}
}
}
dd($unrestrictedPosters);
//return $unrestrictedPosters;
}
}
【问题讨论】:
-
当你 dd($restrictedPoster) 时,输出是什么?
-
我确实得到了一个数组项 {#470 ▼ +"poster_id": 1 +"poster_viewable": "0" +"restricted_country_id": "United Kingdom" }
-
I'm unable to properly access the key value in order to fulfil my if clause.??你没有拿到钥匙来检查我说的对吗? -
试试
if( $restrictedPoster->poster_viewable != 0 ) -
@Newbie 在我的回答中检查一个更好的解决方案,将为您节省查询和循环
标签: php laravel foreach nested-loops