catfan / Medoo

The lightweight PHP database framework to accelerate the development.
https://medoo.in
MIT License
4.83k stars 1.15k forks source link

Feature - Select: set return arr. index as column value #812

Closed keombre closed 5 years ago

keombre commented 5 years ago

Let's say we have this kind of query: ->select("books", ["id [Int]", "author [String]"]); (where id is primary key)

The resulting array looks something like this (JSON notaion): { 0: {"id": 251, "author": "..."}, 1: {"id": 342, "author": "..."}, ... }

Is there any way we could get the entry keys (eg. 0, 1, ...) to match values from one of the columns?

Example: { 251: {"id": 251, "author": "..."}, 342: {"id": 342, "author": "..."}, ... }

For now I've been using foreach to map my primary key column as the array keys. foreach ($db->select("...") as $entry) $data[$entry['id']] = $entry

But this gets tiring very quickly. Since Medoo already has mechanisms for data mapping in select queries, it might not be so difficult to implement.

Proposed query syntax: ->select("books", ["id [Index]", "author [String]"])

mini-fan commented 5 years ago

$data_set = array_column($db->select("..."), 'id');

keombre commented 5 years ago

That just gets 'id' column (in an overcomplicated way), but what if you want all columns just with different indexes?

mini-fan commented 5 years ago

That just gets 'id' column (in an overcomplicated way), but what if you want all columns just with different indexes?

You can encapsulate a simple way to fulfill your needs without having to struggle to add this method to “medoo”, right?

keombre commented 5 years ago

Well I already filed a PR and implementation of this feature was super easy.

Of course, you can loop through all data and modify them to your needs but adding this to Medoo saves you the trouble. Plus, it's faster since Medoo already loops through all the result data.

catfan commented 5 years ago

We do have a plan with this feature for next version, but for this syntax

$datas = $database->select("account", [
    "id" => [
        "user_name",
        "email"
    ]
], [
    "user_id[>]" => 100
]);

If it's using the one key name as first with column array, it will convert id as index.

yoh commented 5 years ago

Why not use PDO::FETCH_UNIQUE for this ?

To get this : $objectsByIds = $database->select('object', ['id', '*']);

In select, I return $query->fetchAll(PDO::FETCH_UNIQUE | PDO::FETCH_CLASS) to have an array of objects [id => object] and in columnPush, I add * in the preg_match for elseif (is_int($key) && is_string($value))

I can do a PR if you want to see this in action ?!