前提・実現したいこと
Laravel5.5にて社員管理システムを作っております。
画像の社員一覧ページにて、今はすべての社員が同じ部署になっていますが、
各社員ごとに異なる部署名を表示させたいと考えております。
1対多 モデル
・Person.php(dept_name以外の要素全て)
・Depart.php(dept_idとdept_nameのみの要素)
発生している問題・エラーメッセージ
Property [dept_id] does not exist on this collection instance.
PersonController.php(該当箇所のみ)
class PersonController extends Controller { public function index(Request $request) { // //peopleテーブルの全レコードを取得する $items = Person::all(); //peopleテーブルの全dept_id $person = Person::select('dept_id')->get(); //「固有ID」personテーブルから出した部署IDに当てはまる部署をBoardテーブルから取得 $dep_relate = \App\Depart::find($person->dept_id); //「全ID」ボードテーブルから部署名全てを取得 // $dep_all = \App\Depart::all(); //部署名以外の情報、共通するIDの部署、全部署名を更新ページへ返す return view( 'person.index', [ 'items' => $items, 'form_person' => $person, //部署以外のデータ // 'form_all' => $dep_all, //全部署名 'form_relate' => $dep_relate //リレーションの部署名 ] ); }
index.blade.php(該当箇所のみ)
@foreach ($items as $item) <tr> <td>{{$item->name}}</td> <td>{{$item->number}}</td> {{-- <td>{{$item->dept_id}}</td> --}} {{-- 部署 --}} @if("{{$item->dept_id}}" === "1") <td>営業部</td> @elseif("{{$item->dept_id}}" === 2) <td>コーポレート部</td> @elseif("{{$item->dept_id}}" === 3) <td>開発部</td> @else <td>メディア部</td> @endif {{$form_relate->dept_name}} {{-- 性別 --}} @if("{{$item->gender}}" == 0) <td>men</td> @else <td>women</td> @endif {{-- <td>{{$form_relate->dept_name}}</td> --}} <td><a href="http://homestead.test/show?id={{$item->id}}">詳細</a></td> <td><a href="http://homestead.test/edit?id={{$item->id}}">更新</a></td> <td><a href="http://homestead.test/del?id={{$item->id}}">削除</a></td> </tr> @endforeach
Depart.php(該当箇所のみ)
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Depart extends Model { public function person(){ return $this->hasMany('App\Person'); } }
Person.php(該当箇所のみ)
class Person extends Model { //guardedは入力の保護を設定するもの protected $guarded = array('id'); public function depart() { return $this->belongsTo('App\Depart'); } //timestampの無効化 public $timestamps = false; }
###create_dept_table.php
class CreateDeptTable extends Migration { public function up() { Schema::create('departs', function (Blueprint $table) { $table->increments('dept_id'); $table->string('dept_name'); }); } public function down() { Schema::dropIfExists('departs'); } }
試したこと
現在はコメントアウトしてしまっていますが、indexの
<td>{{$form_relate->dept_name}}</td> にて、社員それぞれの部署名を表示させたいです。また今の状態で、indexにて代わりに部署名をif文を用いて、表示させようともしたのですが、
全て同じ部署名になってしまっています。
(画像はエラー箇所をコメントアウトして表示した内容です。)
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2019/01/02 16:21
2019/01/02 16:59
退会済みユーザー
2019/01/03 06:20
退会済みユーザー
2019/01/03 06:28
2019/01/04 00:48