我有一个表 Task
,它有 creatorID
和 assignedTo
. 它们都是我的 User
表的主键 u_id
的外键 . 我正在尝试显示 creatorID
和 assignedTo
的名称,但它不起作用,它给出了错误 Trying to get property 'name' of non-object
. 任何能够发现我的代码错误的人?我对我的模型/表格的任何建议或修改都开放了,谢谢 .
Task Table(Migration)
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();
});
User Table(Migration)
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();
});
Task Model
public function users(){
return $this->belongsTo('App\User','u_id');
}
public function assignedTo(){
return $this->belongsTo('App\User','assignedTo');
}
User Model
public function tasks(){
return $this->hasMany('App\Task','u_id');
}
public function assignedTo(){
return $this->hasMany('App\Task','assignedTo');
}
Query
$ActiveTasks = Task::where('p_id',$projectID)->where('status','active')->get();
Blade File
@foreach($ActiveTasks as $task)
<p>{{$task->assignedTo->name}}</p> <<< NOT WORKING
@endforeach
1 回答
在
Task
模型中,您可能需要更新assignedTo()
关系,以便它知道引用u_id
而不是id
:来自docs:
此外,因为您的任务的
assignedTo
列可以为空,所以您可能希望查看在定义关系时可以使用的withDefault()方法: