0
votes

I have relationship between Video Category and Video Courses, one Category can Have many courses, I want to get video courses through video category item but getting error

Video Category Model

class VideoCategory extends Model
{
    public function video_courses(){
        return $this->hasMany('App\VideoCourse');
    }   
}

Video Course Model

class VideoCourse extends Model
{

    public function video_category()
    {
        return $this->belongsTo(VideoCategory::class);
    }

}

My View

@forelse ($category->video_courses as $video_course)
   <a href="#"">{{$course->title}}</a>
@empty
   <p>No Video Courses Available</p>
@endforelse

Error: (4/4) ErrorException SQLSTATE[42S22]: Column not found: 1054 Unknown column 'video_courses.video_category_id' in 'where clause' (SQL: select * from video_courses where video_courses.video_category_id = 2 and video_courses.video_category_id is not null and video_courses.deleted_at is null) (View: C:\xampp\htdocs\QuickLMS\resources\views\category.blade.php)

4
Try it $courses = VideoCategory::find(1)->video_courses. And make sure it returns collection. Then look for the following answers.unclexo

4 Answers

2
votes

In second parameter of each belongsTo and hasMany you must define the foreign key that relates this two tables:

class VideoCourse extends Model
{

    public function video_category()
    {
       return $this->belongsTo(VideoCategory::class, 'video_category_id');
    }

}


class VideoCategory extends Model
{
    public function video_courses(){
        return $this->hasMany(VideoCourse::class,'video_category_id');
    }   
}

The error says you don't have the video_category_id field as foreign key in your table. Pass your foreign key column name in the second parameter.

0
votes

Looks like your table columns don't match your many to one relation. Your video_courses table should have a video_category_id column. That way, each course record references which category it belongs to.

0
votes

If you use a different key for the id make sure you provide that in the relationship method, for example:

public function video_courses() {
    // second parameter is the foreign key.
    return $this->hasMany(VideoCourse::class, 'video_course_id');
}   
0
votes

Provide the key for the relationship in the VideoCategory Model

public function video_courses() {
return $this->hasMany(VideoCourse::class, 'video_course_id');
}