【发布时间】:2019-07-04 14:08:44
【问题描述】:
我正在开发一些 laravel 应用程序,并且我有一个名为“条目”的表格,我在此表格中保存了比赛名称的建议。我需要根据用户总共有多少喜欢的条目对条目进行排序。
这是我的桌子:
id user_id contest_id name liked
1 1 1 test.com true
2 4 1 cool.com false
3 1 1 code.com true
4 3 1 tool123.com false
5 2 1 a23423.com true
6 3 1 dole.net true
7 1 1 great.com false
8 2 1 domain.com true
9 2 1 gol.com false
10 2 1 greatcode.com true
11 2 2 greatco.com true
12 2 2 greatmap.com true
这就是我所拥有的:
$entries = ContestEntry::where('contest_id', '=', $contest->id)
->orderBy('liked', 'desc')
->orderBy('created_at', 'desc')
->get();
我需要通过以下方式订购条目:
给定的 $contest->id(第一行) 是否喜欢该条目(第 2 行) 用户有更多喜欢的条目(全球范围内,而不是当前比赛) 并通过 created_at(第 3 行)
架构:
Schema::create('contest_entries', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('contest_id');
$table->text('name');
$table->text('comment')->nullable();
$table->boolean('liked')->default(false);
$table->boolean('available')->default(true);
$table->timestamp('checked_at');
$table->timestamps();
});
“显示创建表竞赛条目”的输出:
CREATE TABLE `contest_entries` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`contest_id` int(11) NOT NULL,
`name` text COLLATE utf8mb4_unicode_ci NOT NULL,
`comment` text COLLATE utf8mb4_unicode_ci,
`liked` tinyint(1) NOT NULL DEFAULT '0',
`available` tinyint(1) NOT NULL DEFAULT '1',
`checked_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
我需要的是如下表:
id user_id contest_id name liked
5 2 1 a23423.com true
8 2 1 domain.com true
9 2 1 gol.com false
10 2 1 greatcode.com true
1 1 1 test.com true
3 1 1 code.com true
7 1 1 great.com false
4 3 1 tool123.com false
6 3 1 dole.net true
2 4 1 cool.com false
如您所见,它仅显示来自比赛 ID 1 的数据,用户 ID 2 在所有比赛中都有 5 个喜欢 = true 这就是为什么它的条目是第一个,用户 ID 1 有 2 个喜欢 = true 这就是为什么它的条目是第二个......然后继续...
【问题讨论】:
-
你的表架构是什么?
-
请添加
show create table contest_entries的sql输出。 -
您似乎没有
created_at字段。那么你希望如何订购呢? -
laravel 在添加 $table->timestamps() 时添加 created_at 字段;在架构中。
-
"user_id 2 has 5 like = true" -- 我只看到 3 个?? (ID 5,8,10)。请澄清。