Search code examples
phplaravellaravel-4relationshipstable-relationships

Laravel Defining Relationships


I have one table named Content which is a master table like

Content : id content_name created_at updated_at

and another table Course like

Course table have many content_id

Course : id content_id course_name created_at updated_at

I have created relation like this.

Content Model

class Content extends Eloquent {

    protected $table = 'contents';
    protected $guarded = array('id');

    public function course()
    {
        return $this->belongsTo('Course');
    }
}

Course Model

class Course extends Eloquent {

    protected $table = 'courses';
    protected $guarded = array('id');


    public function content()
    {
        return $this->hasMany('Content');
    }
}

When i am fething the data like this $courses=Course::find(1)->content;

It throws error like

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'contents.course_id' in 'where clause' (SQL: select * from contents where contents.course_id = 1)

I am unable to rectify the problem in relations as I am new to laravel.


Solution

  • Close, but you have your relationships backwards. The table that has the foreign key is the one that belongsTo the other one. In this case, your course table has the foreign key content_id, therefore Course belongs to Content, and Content has one or many Courses.

    class Content extends Eloquent {
        public function course() {
            return $this->hasMany('Course');
        }
    }
    
    class Course extends Eloquent {
        public function content() {
            return $this->belongsTo('Content');
        }
    }