RomeNYRR
RomeNYRR

Reputation: 887

Laravel 5 | One to Many Relationship Query Error

I've created a one-to-many relationship between a Jobs Model and Permits model. I've recently discovered the awesome tool of Tinker so I've been using it to test my models. When I run Job::with('steps')->find(1); I get this error

Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'steps.job_id' in 'where clause' (SQL: select * from `steps` where `steps`.`job_id` in (1))'

Here's my Job Model

   public function steps ()
    {
        return $this->hasMany('MyfirstApp\Step');
    }

Here's my Step Model

   public function Job ()
    {
      return $this->belongsTo('MyFirstApp\Job');
    }

I've already set up the foregin key in the Jobs Table so I'm not sure what the error can be. Any ideas?

Table Structure for reference enter image description here

Upvotes: 0

Views: 574

Answers (2)

Jay Dhameliya
Jay Dhameliya

Reputation: 1699

Try it

You are set wrong relationship on model

Job Model

public function steps ()
    {
        return $this->belongsTo('MyfirstApp\Step');
    }

Step Model

public function Job ()
    {
      return $this->hasMany('MyFirstApp\Job');
    }

Upvotes: 1

Raviraj Chauhan
Raviraj Chauhan

Reputation: 653

For your relationship, Job has many Steps, you have assigned wrong foreign key.

In your case steps table should contain job_id rather than job contains steps_id.

Solution:

  • Remove steps_id from job table.
  • Set job_id in steps table as a foreign key.

Upvotes: 1

Related Questions