CakePHP: отображаемое имя вместо идентификатора в связанных таблицах - PullRequest
0 голосов
/ 04 января 2019

Я новый разработчик в CakePHP и PHP.

У меня есть 2 таблицы: Tasks, Users и Customers.

Среди прочего Tasks имеет этот внешний ключ, связанный с таблицей Users: Assigned_from и внешний ключ Customer_id, связанный с таблицей Customers.

Итак, в UsersTable.php я вставил следующие строки:


Функция инициализации:

$this->hasMany('TasksFrom', [
            'foreignKey' => 'assigned_From',
            'className' => 'Tasks'
        ]);

Функция buildrules:

$rules->add($rules->existsIn(['assigned_from'], 'TasksFrom'));

Соответственно в TasksTable.php : Функция инициализации:

$this->belongsTo('UsersFrom', [
        'foreignKey' => 'assigned_from',
        'className' => 'Users'
    ]);

Функция buildrules:

$rules->add($rules->existsIn(['assigned_from'], 'UsersFrom'));

И в CustomersTable.php :

Функция Initialize:

$this->hasMany('Tasks', [
            'foreignKey' => 'customer_id'
        ]);

Поэтому, чтобы показать эту информацию в представлении пользователя, я добавил эти строки в UsersController.php :

public function view($id = null)
{
    $user = $this->Users->get($id,[
        'contain' => ['TasksTo', 'TasksFrom', 'TasksBy']
    ]); 
    $this->set('user', $user);
}

Как я могу изменить свой код для отображения имени пользователя вместо идентификатора пользователя при доступе к echo $task->assigned_from и имени клиента вместо Customer_id при доступе к echo $task->customer_id?

Вот текущий код в users / view.ctp :

foreach ($user->tasks_to as $task) {


            ?>
                <tr  id="<?php echo $task['id'] ?>">
                    <td><?php echo $task->priority ?></td>
                    <td><?php echo $task->name ?></td>
                    <td><?php echo $task->instructions ?></td>
                    <td><?php echo $task->assigned_from ?></td>   //It displays user id, I want to display user name
                    <td><?php echo $task->customer_id ?></td>     //Display Customer name instead of Customer_id
                    <td><?php echo $task->progress ?></td>                            
                </tr>
            <?php } ?>

Отладка вывода отладки ($ user-> tasks_to) :

(int) 1 => object(App\Model\Entity\Task) {

        'id' => (int) 2,
        'name' => 'Design Logo for Website',
        'task_type_id' => (int) 1,
        'role_id' => (int) 5,
        'instructions' => 'Design logo for website.com website, (instructions)',
        'date_start' => object(Cake\I18n\FrozenDate) {

            'time' => '2018-12-20T00:00:00+00:00',
            'timezone' => 'UTC',
            'fixedNowTime' => false

        },
        'date_end' => object(Cake\I18n\FrozenDate) {

            'time' => '2018-12-22T00:00:00+00:00',
            'timezone' => 'UTC',
            'fixedNowTime' => false

        },
        'total_minutes' => (int) 120,
        'assigned_to' => (int) 1,
        'assigned_from' => (int) 1,
        'customer_id' => (int) 1,
        'progress' => null,
        'progress_weight_id' => (int) 2,
        'priority' => (int) 1,
        'status_id' => (int) 2,
        'shared_folder_path' => 'path_to_logo_files',
        'created_by' => null,
        'created_date' => null,
        'price' => (float) 0,
        'cost' => (float) 0,
        'project_status' => object(App\Model\Entity\ProjectStatus) {

            'id' => (int) 2,
            'status' => 'Running',
            '[new]' => false,
            '[accessible]' => [
                'status' => true
            ],
            '[dirty]' => [],
            '[original]' => [],
            '[virtual]' => [],
            '[errors]' => [],
            '[invalid]' => [],
            '[repository]' => 'ProjectStatus'

        },
        '[new]' => false,
        '[accessible]' => [
            'name' => true,
            'task_type_id' => true,
            'role_id' => true,
            'instructions' => true,
            'date_start' => true,
            'date_end' => true,
            'total_minutes' => true,
            'assigned_to' => true,
            'assigned_from' => true,
            'customer_id' => true,
            'progress' => true,
            'progress_weight_id' => true,
            'priority' => true,
            'status_id' => true,
            'shared_folder_path' => true,
            'created_by' => true,
            'created_date' => true,
            'price' => true,
            'cost' => true,
            'task_type' => true,
            'role' => true,
            'users_to' => true,
            'users_from' => true,
            'users_by' => true,
            'user' => true,
            'customer' => true,
            'progress_weight_label' => true,
            'project_status' => true,
            'transactions' => true
        ],
        '[dirty]' => [],
        '[original]' => [],
        '[virtual]' => [],
        '[errors]' => [],
        '[invalid]' => [],
        '[repository]' => 'TasksTo'

    }
]

1 Ответ

0 голосов
/ 04 января 2019
<td><?php echo $task->assigned_from ?></td>   
//It displays user id, I want to display user name

Что-то вроде:

<?= $task->users_from->name ?>

и

<td><?php echo $task->customer_id ?></td>
//Display Customer name instead of Customer_id

как:

<?= $task->customers->name ?>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...