phplaravel-4eloquentrelationships

Laravel fetching eloquent relationship throws static method error


Hi I'm using Laravel 4 and I have three models, Project (table name projects), Status (tables name: statuses) and AssignedProjectBoardStatus (table name: assigned_project_board_statuses). Now when I create a project statuses are automatically assigned if they are not selected from a list. The assigned_project_board_statuses table has two foreign keys the table schema is below:

id|project_id|status_id|order|created_at|updated_at

project_id and status_id are the foreign keys. Now I have a model as so:

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');
    }

There when I am fetching the projects and I want to see the statuses assigned I would call this as follows:

Project::assignedScrumBoardStatuses();

However this throws the following error:

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

So I've changed the function as follows:

app/models/Project.php

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

However this then threw the following error:

Using $this when not in object context

So i then changed the function as follows:

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

And this then threw this error:

Non-static method Illuminate\Database\Eloquent\Model::hasMany() should not be called statically

Any ideas what I'm doing wrong and how I can get the assigned statuses from the model??


Solution

  • You can’t call Project::assignedScrumBoardStatuses() because when you do, the Project model doesn’t know which record you’re trying to fetch the assigned scrum board status for. It has no context.

    Instead, find a record so you have a model instance, and you can then call your relation methods on that:

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