Laravel模型上的自定义查找方法应该是静态的吗?

Gaz*_*zer 5 php methods laravel eloquent

在下面的Laravel 5模型中,该findByIdAndCourseOrFail方法应该是静态的吗?

class Section extends Model {

    //should this method be static?
    public function findByIdAndCourseOrFail($id, $courseId)
    {

        $result = $this->where('id', $id)->where('course_id', $courseId)->first();

        if (!is_null($result))
        {
            return $result;
        }

        throw (new ModelNotFoundException())->setModel(Section::class);

    }


    }
Run Code Online (Sandbox Code Playgroud)

使用控制器:

class SectionsController extends Controller {

protected $sections;

public function __construct(Section $section)
{

    $this->sections = $section;

}

public function foo($id, $courseId)  //illustration only
{
     $section = $this->sections->findOrFail($id);   

     $section = $this->sections->findByIdAndCourseOrFail($id, $courseId);  
     //would need to be non-static

     $section = Section::findByIdAndCourseOrFail($id, $courseId); 
     //weird when compared with find above
}
Run Code Online (Sandbox Code Playgroud)

一方面,我们不是在一个Section实例上行动[见注释].另一方面,在通过Laravel的服务容器进行自动依赖注入的控制器中,我们将对一个实例进行操作:$sections = $this->sections-> findByIdAndCourseOrFail(7,3);我的IDE(PhpStorm)会发出一声叫声Static.

[注意]:这条评论可能是对Laravel模型如何运作的误解.对我来说,我会认为find(),findOrFail()是类方法和反对的实例,一个find方法将返回由此静态.

Pau*_*gel 1

我不确定本地范围是否应该这样使用。但它在 laravel 5.2 上对我有用:

public function scopeFindByIdAndCourseOrFail($query, $id, $courseId)
{
    $result = $query->where('id', $id)->where('course_id', $courseId)->first();

    if (!is_null($result))
    {
        return $result;
    }

    throw (new ModelNotFoundException())->setModel(Section::class);
}
Run Code Online (Sandbox Code Playgroud)

在控制器中,您可以两种方式使用它:

$section = Section::findByIdAndCourseOrFail($id, $courseId);
Run Code Online (Sandbox Code Playgroud)

或者

$model = new Section();
$section = $model->findByIdAndCourseOrFail($id, $courseId);
Run Code Online (Sandbox Code Playgroud)