前提・実現したいこと
PHP(Laravel5.6)でイベントの出席管理のシステムを作っています。
- PHP7.2
- Laravel5.6
- MySQL5.6
会員情報というテーブルとイベント情報というテーブルを作って、イベントに参加した人を中間テーブルに記録しています。
usersテーブル
id | name | age |
---|---|---|
1 | 一郎 | 30 |
2 | 次郎 | 29 |
3 | 三郎 | 28 |
eventsテーブル
id | name | date |
---|---|---|
1 | テスト会1 | 2018/09/01 |
2 | テスト会2 | 2018/09/10 |
user_eventテーブル
|id|user_id|event_id|attendance_status|
|:--|:--:|--:|
|1|1|2|attend|
|2|1|1|absence|
|3|2|1|attend|
|4|2|2|attend|
(※user_eventテーブルのuser_id と event_id は各テーブルのidを外部キーとして作成。)
会員情報とイベント情報はそれぞれ「一覧・詳細・編集・作成」ページを作っています。
イベント情報の「詳細」ページでそのイベントに参加(attend)しているユーザ情報を出力したいと思っています。
しかし、中間テーブルからユーザー情報を出力することができず詰まっています。
該当のソースコード
app/Events.php
class Event extends Model { protected $table = "events"; protected $fillable = [ 'name', 'date', ]; public function userevents() { return $this->belongsToMany('App\UserEvent'); } }
app/Users.php
class User extends Authenticatable { protected $fillable = [ 'name', 'age', ]; public function userevents() { return $this->belongsToMany('App\UserEvent'); } }
app/UserEvent.php
class UserEvent extends Model { protected $table = "user_event"; protected $PrimaryKey = "id"; protected $fillable = [ 'user_id','event_id','attendance_status', ]; public function users() { $users = User::all(); return $this->belongsToMany('App\User'); } public function events() { $events = Event::all(); return $this->belongsToMany('App\Event'); } }
app/Http/Controller/EventController.php
namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\DB; use App\Event; use App\User; use App\UserEvent; class EventController extends Controller { public function show(Event $event, Userevent $userevent, User $user) { //参加者を表示する $userevents = UserEvent::all(); return view('events.show', ['event' => $event, 'userevents' => $userevents]); } }
resources/views/events/show.blade.php
<h2>{{ __('イベントの参加者') }}</h2> <div class="table-responsive"> <table class="table table-striped"> <thead> <tr> <th>{{ __('名前') }}</th> <th>{{ __('年齢') }}</th> <th></th> </tr> </thead> <tbody> <tr> @foreach($userevents as $userevent) @foreach($userevent->users as $user) <td>{{ $user->name}}</td> <td>{{ $user->age}}</td> @endforeach @endforeach </tr> </tbody>
出たエラー
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'サーバー名.user_user_event' doesn't exist …
試したこと
コントローラに下記を入れると、ユーザー情報が表示されますが、user_eventテーブルに登録されていない三郎まで出力されます。
foreach($userevents as $userevent) { $userevent->users = User::all(); }
また、show.blade.phpで
$userevent->users->name
を出力しようとしても、
Property [name] does not exist on this collection instance.
となってしまいます。
モデルでの多対多の指定方法が間違っているのか、コントローラでの書き方が間違っているのか、この2つのどちらかに問題があると思っているのですが、アドバイスいただけないでしょうか?
よろしくお願いいたします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/09/06 13:28