S
S
Sergey Erin2022-01-09 13:35:45
PHP
Sergey Erin, 2022-01-09 13:35:45

How to choose a more correct code solution?

Good day! The Search.php search model has a method for getting an array with usernames for further output as a dropdown list in the template

public function getDropDownData(): array
   {
        $data = [];

        $query = self::find()->select('id')->distinct()->all();

        foreach ($query as $user) {
            $data[$user->id] = $user->getName();
        }

        return $data;
    }


In addition to the username, it is necessary to display the name of the company next to it in brackets from the associated table. I modified the method and did this
foreach ($query as $user) {
            $data[$user->id] = $user->getName() . ' (' . $user->company->getName() . ')';
        }

But it seems to me that this method is not very beautiful, since this list will suddenly be needed in another place, but without the name of the company, and the open-closed principle is violated, it seems to me. Tell me how you can solve this problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2022-01-09
@artalexs

Make two methods.
1. User
names 2. User names + companies (sql query: join with the company table)
In the loop, only the formation of a value from the received data

V
Vitaliy K, 2022-01-11
@revenger

IMHO, make two models: Companies.php and Users.php.

$search = Users::find()->with('Companies')->where([условие])->all();

Then parse the resulting array.
I recommend using ArrayHelper

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question