Laravel获取雄辩的关系会引发静态方法错误

时间:2015-07-25 14:23:52

标签: php laravel-4 eloquent relationships

您好我使用Laravel 4并且我有三个模型,Project(表名projects),Status(表名:statuses)和{ {1}}(表名:AssignedProjectBoardStatus)。现在,当我创建项目时,如果未从列表中选择状态,则会自动分配状态。 assigned_project_board_statuses表有两个表模式的外键:

assigned_project_board_statuses

id|project_id|status_id|order|created_at|updated_atproject_id是外键。现在我有一个模型:

status_id

app/models/AssignedProjectBoardStatus.php

class AssignedProjectBoardStatus extends AbstractModel { public function projects() { return $this->belongsTo('Project'); } public function statuses() { return $this->belongsTo('Status'); } }

app/models/Project.php

class Project extends AbstractModel { public function assignedProjectBoardStatus() { return $this->hasMany('AssignedProjectBoardStatus'); }

app/models/Status.php

当我拿到项目并希望看到分配的状态时,我会将其称为:

class Status extends AbstractModel { public function assignedProjectBoardStatus() { return $this->hasMany('AssignedProjectBoardStatus'); }

然而,这会引发以下错误:

Project::assignedScrumBoardStatuses();

所以我改变了以下功能:

Non-static method Project::assignedProjectBoardStatuses() should not be called statically, assuming $this from incompatible context

app/models/Project.php

然而,这会引发以下错误:

class Project extends AbstractModel { public **static** function assignedProjectBoardStatus() { return $this->hasMany('AssignedProjectBoardStatus'); }

所以我随后将功能改为:

Using $this when not in object context

然后这就抛出了这个错误:

public **static** function assignedScrumBoardStatuses() { return **static::**hasMany('AssignedScrumBoardStatus'); }

任何想法我做错了什么以及如何从模型中获取指定的状态?

1 个答案:

答案 0 :(得分:2)

您无法调用Project::assignedScrumBoardStatuses(),因为当您这样做时,Project模型不知道您尝试获取指定的scrum board状态的记录。它没有背景。

相反,找到一条记录,这样你就有了一个模型实例,然后就可以调用你的关系方法:

$project = Project::find($id)->assignedScrumBoardStatuses();