我一直在使用一个查询,该查询需要计算一组相关表中不同组合的项目。
结构为:
imageviews
----------
-imageId
-productId
-time
-browser
-os
clicks
------
clickId
imageId
time
downloads
---------
downloadId
clickId
time
如果我将雄辩的语言用于优先加载并按两个字段分组,则可以看到“点击”关系,但是我无法计算“浏览器”和“操作系统”每对的每个组合的结果。
>>> $deliveries = App\Delivery::with('clicks')->groupBy('browser','os')->get();
我试图用Eloquent的查询汇总计数,但没有成功的结果。例如,我在定义关系的地方添加了三个模型(Imageview,Click,Downloads)。
ImageView.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ImageView extends Model
{
public $timestamps = false;
protected $primaryKey = 'imageId';
protected $keyType = 'string';
public $incrementing = false;
protected $fillable = ['imageId', 'product_id', 'time', 'browser', 'os', 'site'];
public function clicks()
{
return $this->hasMany(Click::class, 'imageId', 'imageId');
}
}
Click.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Click extends Model
{
public $timestamps = false;
protected $primaryKey = 'clickId';
protected $keyType = 'string';
public $incrementing = false;
protected $fillable = ['deliveryId', 'clickId', 'time'];
public function imageview()
{
return $this->belongsTo(App\ImageView::class, 'imageId', 'imageId');
}
public function downloads()
{
return $this->hasMany(App\Install::class, 'clickId', 'clickId');
}
}
Download.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Download extends Model
{
public $timestamps = false;
protected $fillable = ['downloadId', 'clickId', 'time'];
public function click()
{
return $this->belongsTo(App\Install::class, 'clickId', 'clickId');
}
}
我的目标是构建可生成如下结果的JSON:
{
"interval": {
"start": "2018-01-07T14:30:00+0000",
"end": "2018-01-07T18:20:00+0000" },
"data": [ {
"fields": {
"browser": "Chrome",
"os": "Android"
}, "stats": {
"imageviews": 10,
"clicks": 4,
"downloads": 1
}
},
{
"fields": {
"browser": "Safari",
"os": "iOS"
},
"stats": {
"imageviews": 2,
"clicks": 1,
"downloads": 1
}
},
{
"fields": {
"browser": "Chrome",
"os": "iOS"
}
"stats": {
"imageviews": 15,
"clicks": 5,
"downloads": 3
} }
]
}
我怎么能得到这个?如果需要,我很乐意提供其他信息。