Laravel + Mongo DB来自数据库的最新唯一条目

时间:2019-06-05 11:37:51

标签: php laravel mongodb jenssegers-mongodb

我正在一个Laravel + Mongo DB项目中,我们在其中存储这样的数据:

_id                      | machinename | SoftwareKey  | created_at
-----------------------------------------
5cf6c4a7fdce2778e833dd88 | VM007       | TestSoftware | 2017-01-30 13:22:39
-----------------------------------------
5cf6c4a7fdce2778e833324  | VM008       | TestSoftware | 2017-01-30 13:23:42
-----------------------------------------
5cf6c4a7fdce27783244355  | VM009       | TestSoftware | 2017-01-30 13:25:54
-----------------------------------------
5cf6c4a7fdce27723424345  | VM007       | TestSoftware | 2017-01-30 13:25:
-----------------------------------------
5cf6c4a7fdce23432432745  | VM008       | TestSoftware | 2017-01-30 13:25:54
-----------------------------------------
5cf6c4a7fdce27732467876  | VM009       | TestSoftware | 2017-01-30 13:25:33

我需要调整返回该表中所有条目的方法,以仅返回机器名称的最新条目,基本上是返回该部分:

_id                      | machinename | SoftwareKey  | created_at
-----------------------------------------
5cf6c4a7fdce2778e833dd88 | VM007       | TestSoftware | 2017-01-30 13:22:39
-----------------------------------------
5cf6c4a7fdce2778e833324  | VM008       | TestSoftware | 2017-01-30 13:23:42
-----------------------------------------
5cf6c4a7fdce2778324      | VM009       | TestSoftware | 2017-01-30 13:25:54

索引方法:

public function index() {
    $hills = Hill::all();

    return fractal()
        ->collection($hills)
        ->transformWith(new HillTransformer)
        ->toArray();
    }

我发现了this个问题,并尝试调整我的方法:

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Hill;
use App\Transformers\HillTransformer;
use DB;

class HillController extends Controller
{
    public function index() {
       $hills = DB::select("SELECT *
       FROM hills
       JOIN (SELECT machinename, MAX(created_at) created_at
               FROM hills
           GROUP BY machinename) machinenames
         ON machinename = machinenames.machinename
        AND created_at = machinenames.created_at");

        return fractal()
            ->collection($hills)
            ->transformWith(new HillTransformer)
            ->toArray();
    }
}

但是我得到了这个例外:

  

“ message”:“对成员函数prepare()的调用为null”,       “ exception”:“ Symfony \ Component \ Debug \ Exception \ FatalThrowableError”,       “文件”:“ / home / vagrant / code / hilltracking / vendor / laravel / framework / src / Illuminate / Database / Connection.php”,       “行”:326,

还有另一种方法可以做到这一点吗?谢谢!

顺便说一句。我正在使用laravel-mongodb和分形库。

0 个答案:

没有答案