【发布时间】:2018-01-08 23:33:00
【问题描述】:
目前我在从数据透视表访问数据时遇到问题。
这是我的设置,我有 3 个模型:
- 用户
- 频道
- 访问(作为枢轴,包含 user_id 和 channel_id)
我使用以下方式设置关系:
public function channels()
{
return $this->belongsToMany('App\Models\Channel', 'cms_access', 'user_id', 'channel_id')
->withPivot('access_analytic', 'access_live_channel', 'access_linear_channel', 'access_ads', 'access_push_notification')
->withTimestamps();
}
我尝试构建一个页面来显示用户的详细信息以及他/她对表格的访问权限:
public function show($id)
{
$user = User::findOrFail($id);
// whereHas seems not working, cannot filter to specific id only
$channels = Channel::with('users')
->whereHas('users', function ($query) use($user) {
$query->where('users.id', '=', $user->id);
})
->where('company_id', '=', $user->company_id)
->where('active', '=', 1)
->get();
return view('user.show')
->with('user', $user)
->with('channels', $channels);
}
当前使用表:
<tbody>
@forelse ($channels as $channel)
{!! Form::open(['route' => ['access.store'], 'method' => 'POST']) !!}
<tr>
<td>
<img src="{{ minio_url('channels/'.$channel->logo) }}" alt="{{ $channel->logo }}" class="img-responsive">
</td>
<td>{{ $channel->name_eng }}</td>
<td>
{!! Form::select('access_analytic', ['none' => 'None', 'read' => 'Read'], @$channel->users[0]->pivot->access_analytic, ['class' =>'form-control']) !!}
</td>
<td>
{!! Form::select('access_live_channel', ['none' => 'None', 'read' => 'Read', 'read/write' => 'Read/Write', 'read/write/delete' => 'Read/Write/Delete'], @$channel->users[0]->pivot->access_live_channel, ['class' =>'form-control']) !!}
</td>
<td>
{!! Form::select('access_linear_channel', ['none' => 'None', 'read' => 'Read', 'read/write' => 'Read/Write', 'read/write/delete' => 'Read/Write/Delete'], @$channel->users[0]->pivot->access_linear_channel, ['class' =>'form-control']) !!}
</td>
<td>
{!! Form::select('access_push_notification', ['none' => 'None', 'read' => 'Read', 'read/write' => 'Read/Write', 'read/write/delete' => 'Read/Write/Delete'], @$channel->users[0]->pivot->access_push_notification, ['class' =>'form-control']) !!}
</td>
<td class="text-center">
{!! Form::hidden('user_id', $user->id) !!}
{!! Form::hidden('channel_id', $channel->id) !!}
{!! Form::submit('Save', ['class' =>'btn btn-primary']) !!}
</td>
</tr>
{!! Form::close() !!}
@empty
<tr>
<td colspan="6" class="text-center">No channel available!</td>
</tr>
@endforelse
</tbody>
我不想使用 $channel->users[0]->pivot->access_analytic 等,因为它不能一直工作 由于 whereHas 不工作,有时实际用户位于 users[1],关于我应该如何访问关系的任何其他建议?
【问题讨论】:
标签: laravel laravel-5 eloquent pivot-table laravel-eloquent