Php id中的“显示名称”为“我”;试图获得财产';项目名称';“非对象”的定义;
我有一个表格,其中我提交了一个来自“项目”的id 这些是我的亲戚: 项目模式Php id中的“显示名称”为“我”;试图获得财产';项目名称';“非对象”的定义;,php,laravel,eloquent,eloquent-relationship,Php,Laravel,Eloquent,Eloquent Relationship,我有一个表格,其中我提交了一个来自“项目”的id 这些是我的亲戚: 项目模式 class Project extends Model { protected $primaryKey = 'proj_id'; protected $fillable = ['proj_title','proj_desc','client_id','created_by']; public function client (){ return $this->belo
class Project extends Model
{
protected $primaryKey = 'proj_id';
protected $fillable = ['proj_title','proj_desc','client_id','created_by'];
public function client (){
return $this->belongsTo('App\Client');
}
public function tasks (){
return $this->hasMany('App\Task');
}
}
任务模型
class Task extends Model
{
protected $primaryKey = 'task_id';
protected $fillable = ['task_title','task_desc','status','priority','person_id','proj_title','proj_id','created_by'];
public function project(){
return $this->belongsTo('App\Project','proj_id');
}
}
提前谢谢去吧
{{$task->project->proj_title}
它应该可以正常工作,因为任务和项目之间有关系,所以您应该能够使用$task->project
获得与$task
相关的项目模型,在索引页的某个地方定义了$projects
?你是说Project::find($task->proj_id)->proj_title
?在我进行了新的迁移之后,它对我很有用,谢谢。顺便说一句,我有一个与“created_by”相同的场景,这是一个用户id,我需要显示具有该id的用户的名称。关系是相同的,但使用此^^^^^代码,我尝试获取非-object@Jesus在这种情况下,请检查您从$task->project
中得到了什么。我得到了对于$task->user->name
“正在尝试获取非对象的属性'name'”。如果我离开$task->name
,该字段将保持空白,但不会给出error@Jesus任务模型和用户模型有什么关系吗?我刚想出来。我必须指出我的外键。非常感谢你,你的回答真的很有帮助!
public function index()
{
return view('tasks.index', [
'task' => Task::all(),
'projects' => Project::all(),
]);
}
class Project extends Model
{
protected $primaryKey = 'proj_id';
protected $fillable = ['proj_title','proj_desc','client_id','created_by'];
public function client (){
return $this->belongsTo('App\Client');
}
public function tasks (){
return $this->hasMany('App\Task');
}
}
class Task extends Model
{
protected $primaryKey = 'task_id';
protected $fillable = ['task_title','task_desc','status','priority','person_id','proj_title','proj_id','created_by'];
public function project(){
return $this->belongsTo('App\Project','proj_id');
}
}