[英]Laravel 5.7 Multiple foreign key referencing to same table primary key
我有一個表Task
那里設有creatorID
和assignedTo
。 它們都是User
表主鍵u_id
外鍵。 我想顯示的名稱creatorID
和assignedTo
,但它不能正常工作,它給了一個錯誤Trying to get property 'name' of non-object
。 有人能發現我的代碼有什么問題嗎? 我願意接受任何對我的模型/表的建議或修改,謝謝。
任務表(遷移)
Schema::create('tasks', function (Blueprint $table) {
$table->increments('t_id');
$table->string('t_name');
$table->date('start_date');
$table->date('end_date');
$table->string('status');
$table->unsignedInteger('creatorID');
$table->unsignedInteger('assignedTo')->nullable();
$table->unsignedInteger('p_id');
$table->foreign('creatorID')->references('u_id')->on('users');
$table->foreign('assignedTo')->references('u_id')->on('users');
$table->foreign('p_id')->references('p_id')->on('projects');
$table->string('priority');
$table->timestamps();
});
用戶表(遷移)
Schema::create('users', function (Blueprint $table) {
$table->increments('u_id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->string('status');
$table->string('picture');
$table->timestamps();
});
任務模型
public function users(){
return $this->belongsTo('App\User','u_id');
}
public function assignedTo(){
return $this->belongsTo('App\User','assignedTo');
}
用戶模型
public function tasks(){
return $this->hasMany('App\Task','u_id');
}
public function assignedTo(){
return $this->hasMany('App\Task','assignedTo');
}
詢問
$ActiveTasks = Task::where('p_id',$projectID)->where('status','active')->get();
刀片文件
@foreach($ActiveTasks as $task)
<p>{{$task->assignedTo->name}}</p> <<< NOT WORKING
@endforeach
您可能需要更新Task
模型中的assignedTo
關系,以便它知道引用u_id
而不是id
:
public function assignedTo()
{
return $this->belongsTo(\App\User::class, 'assignedTo', 'u_id');
}
根據文檔:
如果您的父模型不使用id作為其主鍵,或者您希望將子模型連接到其他列,則可以將第三個參數傳遞給belongsTo方法,以指定父表的自定義鍵
https://laravel.com/docs/5.7/eloquent-relationships#defining-relationships
您還應該檢查任務表,以查看任何保存的記錄的assignedTo
列是否為空。 由於設置了nullable
為nullable
屬性,因此在訪問關系時,在assignedTo
具有空值的所有記錄也會產生Trying to get property 'name' of non-object
錯誤的Trying to get property 'name' of non-object
的Trying to get property 'name' of non-object
。 如果是這種情況,可以使用withDefault()
方法定義關系:
belongsTo
關系允許您定義默認模型,如果給定關系為null,則將返回該默認模型。 此模式通常稱為Null對象模式,可以幫助刪除代碼中的條件檢查https://laravel.com/docs/5.7/eloquent-relationships#inserting-and-updating-related-models
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.