使用函数从父表中获取 ID


Getting ID from the Parent table using function

我正在使用Laravel来构建应用程序。我有一个表格课程的模型Course.它idcode都是独一无二的。

有时,我会通过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);