【问题标题】:i get this error: Object of class Illuminate\Database\Eloquent\Builder could not be converted to string in laravel ORM我收到此错误:类 Illuminate\Database\Eloquent\Builder 的对象无法在 laravel ORM 中转换为字符串
【发布时间】:2018-06-16 10:37:47
【问题描述】:

我收到此错误:

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;

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    解决:

    我的原始代码

     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;

    这个查询产生了重复的列

    为此:

    select news.*,count(event_id) as total from news left join solicitud on 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'));
    }
    

    【讨论】:

      【解决方案2】:

      您得到的错误是因为您将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();
      

      【讨论】:

        猜你喜欢
        • 2020-12-01
        • 2020-05-13
        • 2016-05-13
        • 2019-11-29
        • 2022-01-24
        • 2017-03-15
        • 2016-01-01
        • 2019-11-16
        • 2019-01-10
        相关资源
        最近更新 更多