我有这个数据库表: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 Controller 上:
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();
});
}
我在这里做错了吗?
最佳答案
首先,最好从关系定义中删除 id
或声明右 外键
:
class Job extends Model
{
//this
public function pcns(){return $this->hasMany('App\Pcn');}
//or this
public function pcns(){return $this->hasMany('App\Pcn', 'job_id', 'id');}
}
class Department extends Model
{
//this
public function pcns(){return $this->hasMany('App\Pcn');}
//or this
public function pcns(){return $this->hasMany('App\Pcn', 'department_id', 'id');}
}
第二步:最好eager load减少所需查询数量的关系:
public function index()
{
$pcns = Pcn::with(['job', 'department'])->paginate(50);
return view('pcn.index', compact('pcns'));
}
之后,在您看来,您实际上并不需要 @foreach
中的 $key=>$value
:
@foreach($pcns as $pcn)
<td>{{ $pcn->control_number }}</td>
<td>{{ $pcn->job->name }}</td>
<td>{{ $pcn->department->name }}</td>
@endforeach
关于php - 如何在 Laravel 中显示模型关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57607642/