【问题标题】:Call function from model by passing a variable通过传递变量从模型调用函数
【发布时间】:2020-05-14 21:02:03
【问题描述】:

我正在接近 Laravel 7,我猜我迷失在平庸之中。我在模型中创建了一个函数,用于计算一个类别有多少帖子,然后传递 ID 参数。

我在控制器中调用这个函数,然后控制器会在视图中获取变量。

它给了我一个错误:

类 Illuminate\Database\Eloquent\Builder 的对象不能是 转成字符串

我该如何解决?

型号

public function scopeCountActivePostCategory($id)

{
    $query = DB::table('post')->where([
        ['status', 1],
        ['category', $id],
    ]);
    return $query->count();
}

控制器

// get details category by slug
        // preleva dettagli categoria by slug
        $detailCat = DB::table('categories')->where('slug', $slug)->first();

        // get stories
        $post = DB::table('post')
            ->orderByDesc('id')
            ->where('category', $detailCat->id)
            ->where('status', 1)
            ->paginate($set->app_result_x_page);

        return view('category')->with([
            'posts' => $posts, 
            'set' => $set, 
            'totalActivePost' => Post::CountActivePostCategory($detailCat->id),
            'detailCat' => $detailCat
        ]);

【问题讨论】:

    标签: laravel model


    【解决方案1】:

    您的查询中缺少get()。按照您的方式,您尝试计算查询构建器(SQL 查询字符串),而不是通过将 get() 放在构建器末尾来获得的集合。将您的代码更改为:

    public function scopeCountActivePostCategory($id)
    
    {
        $query = DB::table('post')->where([
            ['status', 1],
            ['category', $id],
        ])->get(); //Get here
        return $query->count();
    }
    

    编辑

    CountActivePostCategory 函数的调用也可能是个问题。您正在调用静态函数 CountActivePostCategory,但您没有在 Post 模型中将其定义为静态函数。将您的功能更改为:

    public static function countActivePostCategory($id){
      //body
    }
    

    然后像这样在你的控制器中调用它:

    'totalActivePost' => Post::countActivePostCategory($detailCat->id)
    

    【讨论】:

    • 感谢您的回答,但不幸的是它给了我同样的错误
    • 很高兴我能帮上忙。编码愉快!
    猜你喜欢
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多