2

我目前在 laravel 5 中使用 jenseggers-mongodb eloquent 和 mongodb 3.0.3。我正在尝试加入两个不同的表,如下所示:

用户模型

public function userpayment() {
    return $this->hasMany('App\Models\Userpayment', 'user_id', '_id');
}

用户付费模式

public function user() {
    return $this->belongsTo('App\Models\User','user_id');
}

我正在使用存储库模式

public function __construct() {
    $this->model = new User;
}

return $this->model->with(array('userpayment'=>function($query){
                                $query
                                ->groupBy('dealCodeNumber')
                                ->get();
                    }))
                    ->where('_id',$sid)

                    ->get();

groupBy dealCodeNumber返回 NULL。

array:1 [▼
 0 => array:15 [▼
"_id" => "55813f4cbc59a3f1372e9e6f"
"full_name" => "Varathan"
"username" => "shopsyadmin"
"web_url" => ""
"userpayment" => []
]

没有 groupby 会返回所有。

array:1 [▼
0 => array:15 [▼
"_id" => "55813f4cbc59a3f1372e9e6f"
"full_name" => "Varathan"
"username" => "shopsyadmin"
"userpayment" => array:2 [▼
  0 => array:57 [▼
    "_id" => "55816ce7cc7d4bac0d000029"
    "dealCodeNumber" => "1398410837"
    "inserttime" => "1398411401"
    "status" => "Pending"
  ]
  1 => array:57 [▶]
]

使用 groupby 查询日志

[query] => shopsy_user_payment.aggregate([{"$match":{"user_id":{"$in":["55813f4cbc59a3f1372e9e6f"]}}},{"$group":{"_id":{"dealCodeNumber":"$dealCodeNumber"}

为什么groupby返回null?

4

1 回答 1

2

要对列进行分组,必须在分组之前选择它。将代码更改为以下工作:

return $this->model->with(array('userpayment'=>function($query){
    $query
        ->select('product_id','user_id','dealCodeNumber')
        ->groupBy('dealCodeNumber')
        ->get();
}))
    ->where('_id',$sid)
    ->get();
于 2015-07-14T14:13:23.223 回答