【问题标题】:Laravel 7 leftJoin, Distinct and Sorted by related created_atLaravel 7 leftJoin, Distinct and Sorted by related created_at
【发布时间】:2020-08-01 17:49:55
【问题描述】:

我正在使用 Laravel 7 开发一个专门用于二手视频游戏的列表广告网站。我有一个“游戏”表和一个“列表”表。

游戏

CREATE TABLE `games` (
 `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
 `title` text COLLATE utf8mb4_unicode_ci NOT NULL,
 `slug` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `deleted_at` timestamp NULL DEFAULT NULL,
 `created_at` timestamp NULL DEFAULT NULL,
 `updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
FULLTEXT KEY `fulltext_index` (`title`)
) ENGINE=InnoDB AUTO_INCREMENT=10230 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

列表

CREATE TABLE `listings` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) unsigned NOT NULL,
`game_id` bigint(20) unsigned NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `listings_user_id_foreign` (`user_id`),
KEY `listings_game_id_foreign` (`game_id`),
CONSTRAINT `listings_game_id_foreign` FOREIGN KEY (`game_id`) REFERENCES `games` (`id`) ON DELETE CASCADE,
CONSTRAINT `listings_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=412 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

我需要一个所有“游戏”(不是列表)的分页列表,这些列表按附加的最新“列表”的“created_at”列排序。

感谢帮助解决其中一个问题的 @mayankmodi,我更新了下面的部分以专注于排序问题。

如果我在我的游戏控制器中这样做:

$games = Game::leftJoin('listings', function($leftJoin)
 {
 $leftJoin->on('listings.game_id', 'games.id')
 ->whereNull('listings.deleted_at');
 })
->select('games.*', 'listings.created_at')
->orderByDesc('listings.created_at')
->groupBy('games.id')
->with(['listings' => function ($query) {
$query->latest();
}])
->simplePaginate(36);

我的游戏是不同的,但不是按最后附加的listing.created_at 排序的。

你知道如何解决这个问题吗?

【问题讨论】:

  • @Strawberry :感谢您的意见。现在好点了吗?
  • 嗨。没有。还没有。
  • 谢谢@mayankmodi!它使错误消失。因此,GAMES 尚未按最后一个 LISTING.CREATED_AT 排序。我还在调查。
  • @OMP 谢谢.... 尝试在 ->simplePaginate(36); 之前调用 ->orderByDesc('listings.created_at');

标签: mysql laravel group-by left-join distinct


【解决方案1】:

好的,我让它按预期工作。

如果任何人都可以从 4 小时以上的尝试中受益,我会将我的解决方案粘贴在这里。

$games = Game::leftJoin('listings', function($leftJoin){
 $leftJoin->whereNull('listings.deleted_at')
 ->on('listings.game_id', 'games.id');
 })
->select('games.*', DB::raw('MAX(listings.id) AS latest_listing'))
->groupBy('games.id')
->orderByDesc('latest_listing')
->with('listings')
->simplePaginate(36);

感谢您的帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 2014-12-29
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多