--我有以下3个表,其中包含relationship 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‘的特写文章,下面是
--------------------------------
post_id | user_id | featured
--------------------------------
1 | 1 | Y
1 | 2 | Y
--------------------------------我需要的是显示所有用户复选框5用户,无论他们是否有特色的帖子,并由拉拉8,和那些有特色的用户显示一个复选框。我希望我能说清楚。
发布于 2021-03-31 06:27:58
您应该在Users上使用join使其更简单:
控制器
$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>
@endforeachhttps://stackoverflow.com/questions/66876408
复制相似问题