【问题标题】:Laravel model function best pricketsLaravel 模型函数最佳价格
【发布时间】:2021-03-25 23:14:03
【问题描述】:

我是 Laravel 的新手,我有一个问题如下 我在类别模型查询中检查类别是否存在 如下

 public function scopeIsExist($query ,$id)
    {
        return $query->where(['deleted' => 1, 'id' => $id])->orderBy('id', 'DESC')->first();
    }

我的控制器是

    public function edit($id)
    {


        $dataView['category'] = Category::IsExist($id);    

        if(!$dataView['category'])
        {
            return view('layouts.error');
        }else{
            $dataView['title'] = 'name';
            $dataView['allCategories'] = Category::Allcategories()->get();
            return  view('dashboard.category.edit')->with($dataView);
        }

    }

我的问题是当我使用方法 isEXIST 时,如果 id 没有找到它不会重定向到错误页面,但是我删除 ISEXIST 并替换它如下

$dataView['category'] = Category::where(['deleted' => 1, 'id' => $id])->orderBy('id', 'DESC')->first();

它运作良好。 谁能帮帮我

【问题讨论】:

    标签: laravel laravel-5 eloquent laravel-4


    【解决方案1】:

    这是因为本地作用域应该返回一个\Illuminate\Database\Eloquent\Builder 的实例。您应该删除范围内的first() 并将其放入控制器中。
    像这样重新定义您的范围:

    public function scopeIsExist($query ,$id)
        {
            return $query->where(['deleted' => 1, 'id' => $id])->orderBy('id', 'DESC');
        } 
    

    在您的控制器编辑方法中:

        $dataView['category'] = Category::IsExist($id)->first();    
    

    您可以查看文档以了解本地范围 https://laravel.com/docs/8.x/eloquent#local-scopes

    【讨论】:

      猜你喜欢
      • 2020-01-28
      • 2015-04-16
      • 2012-09-11
      • 1970-01-01
      • 2014-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多