Laravel 7 leftJoin, Distinct and Sorted by related created_a



我正在开发一个列表广告网站,专门用于使用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;

我需要附上一个按最新"LISTING"的"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);

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

你知道怎么解决这个问题吗?

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

如果有人能从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);

谢谢你的帮助!

最新更新