laravelを学習中です。アドバイス頂けたらと思います。
employees
id
dept_id
name
deptsテーブル
id
dept_name
・従業員は、一つの部署に所属する。
・部署は、複数の従業員をもつ。
Employeeモデルクラスに
public function dept() { return $this->belongsTo(Dept::class); }
を追加する。
web.phpでの検証
php
1Route::get('/belongsto',function(){ 2 $employees = App\Employee::all(); 3 foreach($employees as $employee) 4 { 5 echo $employee->dept->dept_name." ".$employee->name."<br>"; 6 } 7 return; 8});
この場合、部署と名前の一覧が取得・表示できました。
その後、コントローラー(EmployeeController)とビューファイルを作成し、
php
1 function index() 2 { 3 $employees = Employee::all(); 4 return view('employee.belongsto',compact('employees')); 5 }
として、
belongsto.blade.phpにて
@foreach($employees as $employee) <p>{{ $employee->dept->dept_name }}</p> <p>{{ $employee->name }}</p> @endforeach
とすると、
Trying to get property 'dept_name' of non-object
とエラーが出てしまいます。
route/web.phpと同じように
$employ->dept->dept_name
とアクセスするのは間違っているのでしょうか?
関連テーブルの値をビューに渡すのはどのようにするのがいいのでしょうか?
宜しくおねがいします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/06/16 14:04
退会済みユーザー
2018/06/16 14:22
2018/06/16 14:35
退会済みユーザー
2018/06/16 14:44 編集
2018/06/16 14:46
2018/06/16 14:58 編集
退会済みユーザー
2018/06/16 15:31
2018/06/16 15:46
退会済みユーザー
2018/06/16 15:54 編集
2018/06/16 16:34
退会済みユーザー
2018/06/16 17:01
2018/06/16 17:51
退会済みユーザー
2018/06/17 06:44
2018/06/17 06:51 編集
退会済みユーザー
2018/06/17 06:52
2018/06/17 07:06 編集
退会済みユーザー
2018/06/17 07:08
2018/06/17 10:24
退会済みユーザー
2018/06/17 10:46