[英]How to display Model Relationship in Laravel?
我有此數據庫表: 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();
});
}
我在這里做錯了嗎?
首先,最好從關系定義中刪除id
或聲明正確的 foreign key
:
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');}
}
第二步:最好急於加載關系以減少所需的查詢數量:
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
paginate()
方法不返回Pcn
的集合,而是返回LengthAwarePaginator
,當它變成數組時,它具有索引( total
, per_page
, next_link
....)。
您需要從LengthAwarePaginator
恢復集合。
@foreach($pcns as $pcn)
<td>{{ $pcn->control_number }}</td>
<td>{{ $pcn->job->name }}</td>
<td>{{ $pcn->department->name }}</td>
@endforeach
順便說一句,您應該在查詢中預加載job
和department
關系,以僅向數據庫發送3個請求 ,而不是101個 。
$pcns = Pcn::with(['job', 'department'])->paginate(50);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.