首页 文章

我收到此错误:类laumin的对象\ Database \ Eloquent \ Builder无法在laravel ORM中转换为字符串

提问于
浏览
0

我收到此错误:

类Illuminate \ Database \ Eloquent \ Builder的对象无法转换为字符串

当我运行此代码时:

public function index()
{
    save_resource_url();
    //$items = News::with(['category', 'photos'])->get(); 

    $items = Solicitud::rightjoin(News::with(['category', 'photos']),'news.id','=','solicitud.event_id')->count('*','event_id','as','total')->get();
    return $this->view('news_events.index', compact('items'));
}

我原来的sql查询

SELECT *,count(event_id)as total FROM solicitud RIGHT JOIN news ON news.id = solicitud.event_id group by title;

2 回答

  • 0

    解决:

    我的原始代码

    public function index()
    {
        save_resource_url();
        $items = News::with(['category', 'photos'])->get();         
        return $this->view('news_events.index', compact('items'));
    }
    

    改变我的SQL查询:

    SELECT *,count(event_id)as total FROM solicitud RIGHT JOIN news ON news.id = solicitud.event_id group by title;

    此查询生成了重复的列

    为了这:

    选择新闻 . *,将(event_id)作为新闻中的总数加入solicitud对solicitud.event_id = news.id group by news.id;

    此查询仅显示users表的列以及与'request'表相关的'total'表

    在我的代码转换为雄辩

    public function index()
    {
        save_resource_url();
        $items = News::with(['category', 'photos'])->leftjoin('solicitud','solicitud.event_id','=','news.id')->groupBy('news.id')->select('news.*',DB::raw('count(event_id) as total'))->get();
        return $this->view('news_events.index', compact('items'));
    }
    
  • 0

    您得到的错误是因为您将 Builder 作为第一个参数 News::with(['category', 'photos']) . 它应该只是字符串(表名),如 'news' .

    Click here to read more

    所以查询应该

    $items = Solicitud::rightjoin( 'news','news.id','=','solicitud.event_id')->count('*','event_id','as','total')->get();
    

相关问题