我需要显示的是所有用户复选框,无论他们是否发布了特色文章,laravel 8 [英] What I need is displaying all users checkboxes whether they have featured post or not by laravel 8
本文介绍了我需要显示的是所有用户复选框,无论他们是否发布了特色文章,laravel 8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下3个表,它们之间的关系为ManyToMany
users TABLE
-------------------
id | name
-------------------
1 | userName_1
2 | userName_2
3 | userName_3
4 | userName_4
5 | userName_5
-------------------
posts TABLE
----------------------
id | title
----------------------
1 | title one
1 | title two
1 | title three
----------------------
post_user TABLE
--------------------------------
post_id | user_id | featured
--------------------------------
1 | 1 | Y
1 | 2 | Y
1 | 3 | N
1 | 4 | N
1 | 5 | N
--------------------------------
控制器
$ ausers = User :: All();
$ post = POST :: findOrFail(1);
@foreach ($ausers as $userx) {{-- --}}
@foreach ($post->users as $user)
<tr>
<td>
<input type="checkbox" name="users[]" value="{{-- $user->id --}}" {{ $user->id == $user->pivot->user_id ? 'checked' : '' }}>
<label for="checkbox0">{{ $userx->name }}</label>
</td>
<td>
<input type="checkbox" name="featured[{{-- $user->id --}}]" value="1" {{ $user->pivot->featured ? 'checked' : '' }} >
</td>
</tr>
@endforeach
@endforeach
问题在于,我只会按照以下方式显示具有"Y"值的精选帖子
The problem is that i will display the featured posts with value 'Y' only ass follows
--------------------------------
post_id | user_id | featured
--------------------------------
1 | 1 | Y
1 | 2 | Y
--------------------------------
我需要显示所有用户复选框[5个用户],无论他们是否具有laravel 8的精选帖子,而那些具有精选帖子的用户则显示一个选中的复选框.我希望我清楚.
What I need is displaying all users checkboxes [5 users] whether they have featured post or not by laravel 8, and those users who have featured posts show a checked checkbox. i hope i am clear.
推荐答案
您应该在 Users
上使用join使其更简单:
You should use join on Users
to make it more simple:
Controlller
$post = Post::findOrFail(1); // Class names should follow naming convention: POST -> Post
$users = User::select(['id', 'name', 'user_id', 'featured'])
->leftJoin('post_user', function($join) use($post) {
// Using leftJoin "user_id" and "featured" will be null when user wasn't selected
return $join->on('users.id', '=', 'post_user.user_id')
->where('post_user.post_id', $post->id);
})
->orderBy('name')
->get();
查看
@foreach ($users as $user)
<tr>
<td>
<input type="checkbox" name="users[]" value="{{ $user->id }}" {{ $user->user_id != null ? 'checked' : '' }}>
<label for="checkbox0">{{ $user->name }}</label>
</td>
<td>
<input type="checkbox" name="featured[{{ $user->id }}]" value="1" {{ $user->featured ? 'checked' : '' }}>
</td>
</tr>
@endforeach
这篇关于我需要显示的是所有用户复选框,无论他们是否发布了特色文章,laravel 8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文