Laravel 4 Eloquent 关系
Laravel 4 Eloquent Relationship
我有 2 个表:
`tasks {id, task_name, status_id}`
`statuses {id, status_name }`
一个任务一次只能有一个状态,例如待定、活动、完成、中止等
这是我目前所拥有的。
class Task extends Eloquent
{
public function status
{
return $this->hasOne('Status', 'id');
}
}
当我尝试 $task->status->status_name
时,出现 'Trying to get a property of non object' 错误!
我的状态 class 看起来像这样
class Status extends Eloquent
{
protected $table = 'statuses';
}
你能解释一下为什么我会遇到这个错误吗?
因为你在 Task
table 中得到外键,你可以使用 belongsTo
并且 Eloquent 将在 [=14] 中查找列 status_id
=] table 给你。
public function status
{
return $this->belongsTo('Status');
}
在一对一部分
中获取更多信息http://laravel.com/docs/4.2/eloquent
对于错误Trying to get a property of non object
请确保在 table tasks
的 status_id
列中有一个值在非常记录中。
我有 2 个表:
`tasks {id, task_name, status_id}`
`statuses {id, status_name }`
一个任务一次只能有一个状态,例如待定、活动、完成、中止等
这是我目前所拥有的。
class Task extends Eloquent
{
public function status
{
return $this->hasOne('Status', 'id');
}
}
当我尝试 $task->status->status_name
时,出现 'Trying to get a property of non object' 错误!
我的状态 class 看起来像这样
class Status extends Eloquent
{
protected $table = 'statuses';
}
你能解释一下为什么我会遇到这个错误吗?
因为你在 Task
table 中得到外键,你可以使用 belongsTo
并且 Eloquent 将在 [=14] 中查找列 status_id
=] table 给你。
public function status
{
return $this->belongsTo('Status');
}
在一对一部分
中获取更多信息http://laravel.com/docs/4.2/eloquent对于错误Trying to get a property of non object
请确保在 table tasks
的 status_id
列中有一个值在非常记录中。