drupal8mysql数据库查询

4nkexdtk  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(492)

我有一个自定义模块和一个定义的路径。我想查询一个单独的数据库(在localhost中)并通过响应提取这些数据,以便它显示在模块的.twig页面上。
我正在笔记本电脑上的本地开发环境中工作。只是不能让它工作。我做错什么了?
controller.php文件:

namespace Drupal\career_pathways\Controller;
use Symfony\Component\HttpFoundation\Response;

class PathwaysController{
 public function getPaths(){
  $response = new Response();

   $con = \Drupal\Core\Database\Database::getConnection('career_pathways','default');
   $sql = query("SELECT * FROM {pathways}");
   $result = $query->execute();

   if ($result) {
     while ($row = $result->fetchAll()) {
       // Do something with:
       $response = array(
         '#theme' => 'career_pathways',
         '#title' => 'Career Pathways',
         '#markup' => 'A Career Without Boundaries',
         '#firstname' => $row['firstname'],
         '#lastname' => $row['lastname'],
         '#role' => $row['role'],
         '#company' => $row['company']
       );
     }
   }
return $response;
}
}
nqwrtyyt

nqwrtyyt1#

要在自定义模板文件中显示路线,需要执行以下操作
职业路径.routing.yml

career_pathways.getpaths:
  path: '/getpaths'
  defaults:
    _controller: '\Drupal\career_pathways\Controller\PathwaysController::getPaths'
    _title: 'getPaths'
  requirements:
    _permission: 'access content'

路径控制器.php

namespace Drupal\career_pathways\Controller;
use Symfony\Component\HttpFoundation\Response;

use Drupal\Core\Controller\ControllerBase;

class PathwaysController extends ControllerBase {
 public function getPaths(){
   $query = \Drupal::database()->query( "SELECT * FROM pathways" );
   $results = $query->fetchAll();
   $processedResults=[];
    :
   Process your result here
    :

   $build = [
     '#theme' => 'career_pathways',
      '#results' => $processedResults,
    ];
    return $build;
  }
}

职业途径模块

/**
 * Implements hook_theme().
 */
function career_pathways_theme() {
  return [
    'career_pathways' => [
      'variables' => [
        'results' => NULL,
      ],
      'render element' => 'children',
    ],
  ];
}

模板/career-pathways.html.twig

Hi im working
{{results}}

现在,在正确加载模板之后。添加逻辑并将其传递给 $results 变量

相关问题