Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Antonella's avatar

I would like the last 5 values sorted by date including duplicates.

I have two tables linked by a 1: N relationship

Schema::create('polls', function (Blueprint $table) {
        $table->id();
        $table->text('name');
        $table->text('status');
        $table->timestamps();
    });

    Schema::create('duplicate_polls', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('poll_id');
        $table->timestamps();

        $table->foreign('poll_id')
        ->references('id')
        ->on('polls');
    });

every time a data is inserted with the "name" already present in polls, this data is inserted in duplicate_polls with id, poll_id (id of the name already present in polls) .

I would like the last 5 values sorted by date including duplicates.

ex. Polls +----+----------------+---------------+ | id | name | status|created +----+----------------+---------------+ | 1 | cat | A | 2020-11-19 | 2 | dog | A | 2020-11-20 | 3 horse | B | 2020-11-21 | 4 | bike | C | 2020-11-22 | 5 | kayak | C | 2020-11-23 +-------------+-------+----------------+

duplicate_polls

+----+----------------+---------------+
| id | task_id |created
+----+--------+---------------+
|  1 |  1    |  2020-11-19
|  2 |  1   |   2020-11-20
|  3   4 |   2020-11-23
|  4 | 5    |  2020-11-23
|  5 | 4 |  2020-11-23
+-------------+-------+----------------+


result

+----+----------------+---------------+
| id | name | status|created	|  father
+----+----------------+---------------+
|  5 |  bike   |       C | 2020-11-23|  4
|  2 |  bike  |       A | 2020-11-23| 4
|  3   bike |       B | 2020-11-23| null

eeccc

I had thought about solving this but it doesn't work:

	$a= DB::table('polls')->join('duplicate_polls', 'polls.id', '=', 'duplicate_polls.poll_id')
            ->select('duplicate_polls.id','polls.name','polls.status','duplicate_polls.created_at','duplicate_polls.poll_id','polls.id')
            ->orderBy('duplicate_polls.created_at', 'asc')
            ->paginate(10);
	$b= DB::table('polls')
           ->select('id','name','status','created_at','null as d_id')
            ->orderBy('duplicate_polls.created_at', 'asc')
            ->union('$a')
            ->paginate(10);
0 likes
0 replies

Please or to participate in this conversation.