为什么我无法访问查询中的数据?

时间:2016-01-12 18:04:00

标签: php laravel laravel-4 laravel-5

        $threads = Thread::leftjoin('users', 'users.id', '=', 'threads.user_id')
        ->leftjoin('users as poster','poster.id', '=', 'threads.user_id')
        ->leftjoin('forums_threads', 'forums_threads.thread_id','=','threads.id')
        ->leftjoin('threads_users', 'threads_users.thread_id','=','threads.id');

        if($request->search){
            echo 'Search:' . $request->search;
            $threads->where('title', '=', $request->search);
        }

        if($request->author){
            echo 'author:' . $request->author;
            $threads->where('users.id', $request->author);
        }

        if($request->site){
            echo 'site:' . $request->site;
            $threads->where('threads.source', $request->site);
        }

        $threads->groupBy(array('threads.id', 'users.username','threads_users.boosts', 'users.id'))
        ->get(array('threads.*','users.username','threads_users.boosts'));

如果我对它执行 - > count(),我得到3的回报,这是我所期望的。如果我执行 - > toSql(),我会看到预期的sql语句。但是如果我做像foreach这样的事情($ threads作为$ thread){echo' inside&#39 ;;}我没有显示任何内容。

1 个答案:

答案 0 :(得分:1)

您没有将结果存储在$threads变量中。

要么这样做:

$threads = $threads->groupBy(array('threads.id', 'users.username','threads_users.boosts', 'users.id'))
    ->get(array('threads.*','users.username','threads_users.boosts'));

或创建一个新变量并循环:

$results = $threads->groupBy(array('threads.id', 'users.username','threads_users.boosts', 'users.id'))
    ->get(array('threads.*','users.username','threads_users.boosts'));

foreach ($results as $result) {
    // stuff
}