Attach()从修补程序而不是控制器工作


attach() working from tinker but not controller

我想在同一个类上实现多对多关系。课程有必修课程。Attach可以从tinker中工作,但不能从控制器中工作。

$course->pre_reqs()->attach(int); // works from tinker
//does not work from controller (I checked that $course is the right object)
$course =  DB::table('courses')->where('id', $id1)->first();
$course->pre_reqs()->attach(10);
//from model
public function pre_reqs()
{
    return $this->belongsToMany('App'Course', 'pre_req', 'course_id', 'pre_req_course_id' );
}

透视表与tinker一起工作。

错误是

调用未定义方法pre_reqs

尝试使用Model class

$course =  Course::where('id', $id1)->first();
$course->pre_reqs()->attach(10);