我正在使用Laravel来构建应用程序。我有一个表格课程的模型Course
.它id
和code
都是独一无二的。
有时,我会通过code
来验证某些东西。但是我总是必须使用code
获得该课程的id
。
我在Course
模型中编写了一个函数。
public function getCourseId($code){
return Course::where('code', $code)->pluck('id');
}
但是当我尝试调用该函数时,我没有此类的对象。我只有code
这是表格的一列courses
我试着打电话给$code->getCourseId($code);
但我知道这是不对的。有没有其他方法可以只用$code
调用这个函数?
为了使它起作用,帮助程序函数必须是静态的,因为您不想在 Course
的实例上调用它。试试这个:
public static function getCourseId($code){
$course = static::where('code', $code)->first();
if($course == null){
return null;
}
return $course->id;
}
并这样称呼它:
$id = Course::getCourseId($code);
另外,在我看来,这个名字会更合适:
$id = Course::getIdByCode($code);