我有这样的数据库表:job,department,pcn和该表pcn具有性能job_id及department_id在其上。因此,在 Laravel 中,我对其等效模型有以下定义:
class Job extends Model
{
public function pcns(){return $this->hasMany('App\Pcn', 'id');}
}
class Department extends Model
{
public function pcns(){return $this->hasMany('App\Pcn', 'id');}
}
class Pcn extends Model
{
public function job(){return $this->belongsTo('App\Job');}
public function department(){return $this->belongsTo('App\Department');}
}
我现在的问题是显示 Pcn 列表的 pcn 索引给了我这个错误:
Trying to get property 'name' of non-object (View: C:\wamp\www\bookersystem\resources\views\pcn\index.blade.php)
其中我index.blade.php有这个:
@foreach($pcns as $key => $value)
<td>{{ $value->control_number }}</td>
<td>{{ $value->job->name }}</td>
<td>{{ $value->department->name }}</td>
@endforeach
在我的 Pcn 控制器上:
public function index()
{
$pcns = Pcn::paginate(50);
return view('pcn.index', compact('pcns'));
}
至于我的迁移,我有这个定义:
public function up()
{
Schema::create('pcn', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->charset = 'utf8mb4';
$table->collation = 'utf8mb4_general_ci';
$table->bigIncrements('id');
$table->unsignedBigInteger('department_id');
//$table->foreign('department_id')->references('id')->on('department');
$table->unsignedBigInteger('job_id');
//$table->foreign('job_id')->references('id')->on('job');
$table->string('control_number', 45);
$table->string('center', 5);
$table->string('status', 8)->nullable();
$table->unsignedBigInteger('mrf_id')->nullable();
$table->string('degree', 25)->default('Not Recruiting');
$table->timestamps();
});
}
我在这里做错了吗?
慕标琳琳
jeck猫