[英]Laravel sub-query
我有一个看起来像这样的数据库:👇👇
图片🌅
| id | name | src | status |
| ------------- |---------------| ------------| ----------|
| 1 | nice sun set | 1020288.jpg | published |
| 2 | poor sun set | 1120288.jpg | published |
| 3 | best sun set | 3120288.jpg | deleted |
| ------------- |---------------| ------------| --------- |
image_views 👀
| id | image_id | browser_id🌎 | created_at |
| ------------- |---------------| ------------ | ------------------ |
| 1 | 2 | 1020288e3221 |2020-02-23 13:55:11 |
| 2 | 1 | 1120288221ww |2020-02-27 13:50:51 |
| ------------- |---------------| ------------ | ------------------ |
现在在我的 Laravel 应用程序中,
我想在过去的过去7天的观看次数最多的图片。
(我想要一列 image_views 并且这些视图 👀 应该按浏览器 id 分组)。
所以这是我尝试过的:👇👇
$image_views = DB::table('image_views')
->selectRaw('count(*) as view_count')
->where(function($query){
$query->where('image_views.image_id', 'images.id');
$query->whereDate('image_views.created_at', '>=', Carbon::now()->subDays(7)->toDateTimeString() );
});
$image = Image::select(['images.*', DB::raw('(' . $image_views->toSql() . ') as views ')])
->limit(1)
->orderBy('views', 'desc')
->where('images.status','published')
->mergeBindings($image_views)
->get();
return $image;
所以不幸的是上面发布的☝☝代码不起作用😩
它只返回空白结果。
顺便说一下,从 2⃣0⃣1⃣9⃣ 到现在,我在 image_views 表中有很多视图,只是我不能在这里发布所有..
有趣的是,如果我将其转换为 SQL 并将其粘贴到 PHPMYADMIN 中,它就像一个魅力
return $image->toSql();
//->mergeBindings($image_views)
//->get();
请有人告诉我我在 Laravel 中做错了什么!!🙌
给定images
和image_views
表
$mostViewdImage = DB::table('image_views')
->join('images', 'image_views.image_id', '=', 'images.id')
->select('browser_id', DB::raw('count(image_id) as occurrence'), 'images.*')
->where('image_views.created_at', '>=', Carbon::now()->subDays(7)->toDateTimeString())
->groupBy('image_id', 'browser_id')
->orderByRaw('occurrence DESC')->first();
dump($mostViewdImage);
//Output
"select `browser_id`, count(image_id) as occurrence, `images`.* from `image_views` inner join `images` on `image_views`.`image_id` = `images`.`id` where `image_views`.`created_at` >= ? group by `image_id`, `browser_id` order by occurrence DESC limit 1" (2.02 s)
{#261 ▼
+"browser_id": "1020288e3221"
+"occurrence": 2
+"id": 2
+"name": "poor sun set"
+"src": "1120288.jpg"
+"status": "published"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.