jeudi 20 juin 2019

Union results from multiple tables which are being assigned dynamically

Table names should be passed as parameter (array of strings). I need to get from each table values of same columns foreign_key_id and updated_at, but only most recent ten results (by that I mean those which were last updated). I need to union result from each table. Also, I already have list of foreign_key_ids for which I am searching the tables. The way I have tried doing this:

$foreign_key_ids = ['1', '2', '3', '4'];
$tables = ['table_A', 'table_B', 'table_C'];

foreach ($foreign_key_ids as $foreign_key_id)
{
    $index = 0;

    foreach($tables as $table)
    {
        $query = DB
             ::table($table)
             ->select('foreign_key_id', 'updated_at')
             ->where('foreign_key_id', $foreign_key_id)
             ->orderBy('updated_at', 'desc')
             ->limit(10);

        if ($index == 0)
        {
            $single_table = $query;
        }
        else
        {
            $single_table->union($query);
        }

        $index++;
    }

        $full_result[] = $single_table;
    }

    $final_result = [];

    foreach($full_result as $single_result)
    {
        $final_result->union($single_result);
    }

    $final_result = $final_result->get();
}

But I am getting an exception Call to a member function union() on array and not sure why, cause $single_result in last foreach is not array, it's instance of builder.



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2FmJJRj
via IFTTT

Aucun commentaire:

Enregistrer un commentaire