【问题标题】:how to join tables using tablegateway如何使用 tablegateway 连接表
【发布时间】:2017-11-15 12:39:54
【问题描述】:

使用 tableadapter 时如何在 zend3 中连接表?问题不在于一般如何连接表,而在于如何在 zend 中执行此操作以及将代码放置在何处。

假设我有一个 *table 类,例如:

namespace Import\Model;
use RuntimeException;
use Zend\Db\TableGateway\TableGatewayInterface;

class ProjectTable
{
    private $tableGateway='t_project';

    public function __construct(TableGatewayInterface $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

public function fetchAll()
{
    return $this->tableGateway->select();
}

我想加入两张桌子,我该怎么做,这里是做的正确地方吗?我尝试实现以下功能:

public function Project_Unit(Unit $unit = null){

    $select = $this->tableGateway->getSql()->select()
    ->join('t_unit', 't_project.ProjectID = t_unit.ProjectID',array('UnitID','CI_Number', 'Unitname','Shortcut','Suppliername'));       //, left
    return $this->tableGateway->selectWith($select);

}

我没有收到错误,而是得到了混淆的数据。之后我尝试使用别名也没有用。

我的问题是,如果我需要连接两个表,如何构建这个表类。这些表将是项目 1 -> n 单元(关键项目 ID)。第二个问题是如何正确使用别名,因为我在两个表中都有一些具有不同数据的字段名,例如每个表都有一个列快捷方式。

编辑:新信息 为了查看数据的来源,我重命名了 Exchangearray 的变量:

public function exchangeArray(array $data)
{
    $this->PProjectID= !empty($data['ProjectID']) ? $data['ProjectID'] : null;
    $this->PCI_Number= !empty($data['CI_Number']) ? $data['CI_Number'] : null;
    $this->PDescription= !empty($data['Description']) ? $data['Description'] : null;
    $this->Projectname= !empty($data['Projectname']) ? $data['Projectname'] : null;
    $this->PShortcut= !empty($data['Shortcut']) ? $data['Shortcut'] : null;
    $this->PComponent_Class= !empty($data['Component_Class']) ? $data['Component_Class'] : null;
}

现在我得到了一个有趣的输出(我还添加了我的数据数组的内容)

我有两列名称相同,分别是快捷方式和 ci-number,这些数据字段与 tableadapter 表中的相同字段混合在一起。

U1 不是 galileo 的快捷方式,它是单位的快捷方式。伽利略的捷径应该是GAL。似乎命名相同的列由第二个表(单元)填充,但我不会从表单元中获取任何字段。

编辑:显示我根据 jobaer 的建议所做的补充:

我编辑了我的 ProjectTable 类:

class ProjectTable
{
    //private $tableGateway='t_project';
    private $projectTableGateway;
    private $unitTableGateway;


//  public function __construct(TableGatewayInterface $tableGateway)
//  {
//      $this->tableGateway = $tableGateway;
//  }

public function __construct(
        TableGatewayInterface $projectTableGateway,
        TableGatewayInterface $unitTableGateway)
{
    $this->projectTableGateway = $projectTableGateway;
    $this->unitTableGateway = $unitTableGateway;
}


public function fetchAll()
{

    $sqlSelect = $this->unitTableGateway->getSql()->select();

    /**
     * columns for the "project_table" exactly it is unit_table
     */
    $sqlSelect->columns(array('CI_Number', 'ProjectID','Unitname','Shortcut','Suppliername'));

    /**
     * this can take two more arguments:
     * an array of columns for "unit_table"
     * and a join type, such as "inner"
     */
$sqlSelect->join('t_project', 't_unit.ProjectID = t_project.ProjectID');    


    /**
     * set condition based on columns
     */
    //$sqlSelect->where(array('unit_table.project_id' => $id));

    $resultSet = $this->unitTableGateway->selectWith($sqlSelect);

    return $resultSet;



    //return $this->tableGateway->select();
}

我还按照建议编辑了我的 Module.php,这里有一个 sn-p

    //                      Model\ProjectTable::class => function($container) {
//                          $tableGateway = $container->get(Model\ProjectTableGateway::class);
//                          return new Model\ProjectTable($tableGateway);
//                      },
                        Model\ProjectTable::class => function($container) {
                            $projectTableGateway = $container->get(Model\ProjectTableGateway::class);
                            $unitTableGateway = $container->get(Model\UnitTableGateway::class);
                            return new Model\ProjectTable($projectTableGateway, $unitTableGateway);
                        },

                        Model\ProjectTableGateway::class => function ($container) {
                            $dbAdapter = $container->get(AdapterInterface::class);
                            $resultSetPrototype = new ResultSet();
                            $resultSetPrototype->setArrayObjectPrototype(new Model\Project());
                            return new TableGateway('t_project', $dbAdapter, null, $resultSetPrototype);
                        }

我的控制器操作没有改变:

return new ViewModel([
                        'projects' => $this->projectTable->fetchAll(),
                            ]);

在我看来,我试图抓取两个表的列:

foreach ($projects as $project) : 
    //  $unit=$units->fetchAllP($project->ProjectID);
var_dump(get_object_vars($project));?>
     <tr>
     <td><?= $this->escapeHtml($project->Unitname) ?></td>
     <td><?= $this->escapeHtml($project->Projectname) ?></td>
     <td><?= $this->escapeHtml($project->Shortcut) ?></td>
     <td><?= $this->escapeHtml($project->CI_Number) ?></td>
     <td><?= $this->escapeHtml($project->Description) ?></td>
        <td><?= $this->escapeHtml($project->Component_Class) ?></td>


        <td>
            <a href="<?= $this->url('project', ['action' => 'edit', 'id' => $project->ProjectID]) ?>">Edit</a>
            <a href="<?= $this->url('project', ['action' => 'delete', 'id' => $project->ProjectID]) ?>">Delete</a>
        </td>

<?php endforeach; ?>

我得到了一个有趣的输出,所以仍然缺少一些东西。我希望在两个连接表中都有 al 列。

EDIT2:显示下一个版本

这是我的方法 fetchAll()/class ProjectTable

public function fetchAll()
    {

        $sqlSelect = $this->unitTableGateway->getSql()->select();
        $sqlSelect->columns(array('UnitID','CI_Number', 'ProjectID','Unitname','Shortcut','Suppliername'));
        $sqlSelect->join('t_project', 't_unit.ProjectID = t_project.ProjectID', array('Project' =>'Projectname','CI' =>'CI_Number','PDescription' =>'Description','PShortcut' =>'Shortcut','PComponent' =>'Component_Class','PProjectID' =>'ProjectID'));
        //$sqlSelect->where(array('unit_table.project_id' => $id));
        $resultSet = $this->unitTableGateway->selectWith($sqlSelect);

        //return $resultSet;
        return $resultSet->toArray();

        //return $this->tableGateway->select();

这是我的视图:

<?php 
//var_dump(get_object_vars($projects));
foreach ($projects as $project) : 
//var_dump(get_object_vars($project));

?>
    <tr>
    <td><?= $project['Project']?></td>
    <td><?= $project['CI']?></td>
    <td><?= $project['Unitname']?></td>
  <?php     
 endforeach; ?>

}

这里有一个新的截图:

EDIT3:添加单位材料

class UnitTable
{
    private $tableGateway='t_unit';

    public function __construct(TableGatewayInterface $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    public function fetchAll()
    {
        return $this->tableGateway->select();
    }

类单位也:

class Unit implements InputFilterAwareInterface
{
    public $UnitID;
    public $CI_Number;
    public $ProjectID;
    public $Unitname;
    public $Shortcut;
    public $Suppliername;

    private $inputFilter;

    public function exchangeArray(array $data)
    {
        $this->UnitID= !empty($data['UnitID']) ? $data['UnitID'] : null;
        $this->CI_Number= !empty($data['CI_Number']) ? $data['CI_Number'] : null;
        $this->ProjectID= !empty($data['ProjectID']) ? $data['ProjectID'] : null;
        $this->Unitname= !empty($data['Unitname']) ? $data['Unitname'] : null;
        $this->Shortcut= !empty($data['Shortcut']) ? $data['Shortcut'] : null;
        $this->Suppliername= !empty($data['Suppliername']) ? $data['Suppliername'] : null;
    }

因为我只有sampledata,我的两个表单元和项目的截图

EDIT4:module.php 的工厂部分

public function getServiceConfig()
    {
        return [
                'factories' => [
                        Model\ImportTable::class => function($container) {
                            $tableGateway = $container->get(Model\ImportTableGateway::class);
                            return new Model\ImportTable($tableGateway);
                        },
                        Model\ImportTableGateway::class => function ($container) {
                            $dbAdapter = $container->get(AdapterInterface::class);
                            $resultSetPrototype = new ResultSet();
                            $resultSetPrototype->setArrayObjectPrototype(new Model\Import());
                            return new TableGateway('t_dcl', $dbAdapter, null, $resultSetPrototype);
                        },
                        Model\DclimportTable::class => function($container) {
                            $tableGateway = $container->get(Model\DclimportTableGateway::class);
                            return new Model\DclimportTable($tableGateway);
                        },
                        Model\DclimportTableGateway::class => function ($container) {
                            $dbAdapter = $container->get(AdapterInterface::class);
                            $resultSetPrototype = new ResultSet();
                            $resultSetPrototype->setArrayObjectPrototype(new Model\Dclimport());
                            return new TableGateway('t_dcl_import', $dbAdapter, null, $resultSetPrototype);
                        },
                        Model\FollowupTable::class => function($container) {
                            $tableGateway = $container->get(Model\FollowupTableGateway::class);
                            return new Model\FollowupTable($tableGateway);
                        },
                        Model\FollowupTableGateway::class => function ($container) {
                            $dbAdapter = $container->get(AdapterInterface::class);
                            $resultSetPrototype = new ResultSet();
                            $resultSetPrototype->setArrayObjectPrototype(new Model\Followup());
                            return new TableGateway('t_dcl_wv', $dbAdapter, null, $resultSetPrototype);
                        },
                        Model\UnitTable::class => function($container) {
                            $tableGateway = $container->get(Model\UnitTableGateway::class);
                            return new Model\UnitTable($tableGateway);
                        },
                        Model\UnitTableGateway::class => function ($container) {
                            $dbAdapter = $container->get(AdapterInterface::class);
                            $resultSetPrototype = new ResultSet();
                            $resultSetPrototype->setArrayObjectPrototype(new Model\Unit());
                            return new TableGateway('t_unit', $dbAdapter, null, $resultSetPrototype);
                        },
//                      Model\ProjectTable::class => function($container) {
//                          $tableGateway = $container->get(Model\ProjectTableGateway::class);
//                          return new Model\ProjectTable($tableGateway);
//                      },

                        Model\ProjectTableGateway::class => function ($container) {
                            $dbAdapter = $container->get(AdapterInterface::class);
                            $resultSetPrototype = new ResultSet();
                            $resultSetPrototype->setArrayObjectPrototype(new Model\Project());
                            return new TableGateway('t_project', $dbAdapter, null, $resultSetPrototype);
                        },
                        Model\ProjectTable::class => function($container) {
                            $projectTableGateway = $container->get(Model\ProjectTableGateway::class);
                            $unitTableGateway = $container->get(Model\UnitTableGateway::class);

                            return new Model\ProjectTable($projectTableGateway, $unitTableGateway);
                        }
                        ],
                        ];
    }

【问题讨论】:

    标签: zend-db zend-framework3


    【解决方案1】:

    如果您知道如何处理模型中的两个表,这将非常简单。假设您有 ProjectTable 和 UnitTable 模型和两个 TableGateway 服务。这些将分别处理数据库中的两个表。因此,如果您想将他们加入您的 ProjectTable 模型中,那将是

    ProjectTable.php

    class ProjectTable
    {
        private $projectTableGateway;
        private $unitTableGateway;
    
        public function __construct(
            TableGatewayInterface $projectTableGateway, 
            TableGatewayInterface $unitTableGateway)
        {
            $this->projectTableGateway = $projectTableGateway;
            $this->unitTableGateway = $unitTableGateway;
        }
    
        public function projectUnit($id)
        {
    
            /** 
             * as you are joing with "project_table"
             * this will handle "unit_table" 
             */ 
            $sqlSelect = $this->unitTableGateway->getSql()->select();
    
            /**
             * columns for the "unit_table".
             * if want to use aliases use as 
             * array('alias_name' => 'column_name')
             */
            $sqlSelect->columns(array('column_one', 'column_two'));
    
            /**
             * this can take two more arguments: 
             * an array of columns for "project_table"
             * and a join type, such as "inner"
             */
            $sqlSelect->join('project_table', 'unit_table.project_id = project_table.id');
    
            /**
             * set condition based on columns
             */
            $sqlSelect->where(array('unit_table.project_id' => $id));
    
            $resultSet = $this->unitTableGateway->selectWith($sqlSelect);
    
            return $resultSet; 
        }
    }
    

    现在创建两个TableGateway 服务来处理两个表,并将它们传递给ProjectTable 的构造函数,如下所示

    Model\ProjectTable::class => function($container) {
        $projectTableGateway = $container->get(Model\ProjectTableGateway::class);          
        $unitTableGateway = $container->get(Model\UnitTableGateway::class);
    
        return new Model\ProjectTable($projectTableGateway, $unitTableGateway);          
    }
    

    【讨论】:

    • 我进步了一大步,但它还不能正常工作。输出显示了 unit_table 的列,我可以抓取它们,但在两个表中名称相同的两个列旁边没有找到 project_table 的列。分别是快捷方式和 CI_Number。那么如何获取所有列呢?
    • 您的ProjectTableGateway 没问题,但没有显示您的UnitTableGateway。我评论了在哪里为每个表提供列。但我没有告诉如何使用别名。这是单元表 $sqlSelect->columns(array('alias_name' => 'column_name', ...));这是针对项目表 $sqlSelect->join('t_project', 't_unit.ProjectID = t_project.ProjectID', array('alias_name' => 'column_name', ...));
    • 我试过了,只有一列,只是为了弄清楚。 $sqlSelect->join('t_project', 't_unit.ProjectID = t_project.ProjectID', array('P' => 'Projectname'));我收到一个错误通知:Undefined property: Import\Model\Unit::$P in C:\xampp\htdocs\ohb\module\Import\view\import\import\index.phtml 在第 37 行,我的 vardump 没有显示列。
    • 您应该分配数组中的所有列。否则,它不会返回所有列的结果。在模型方法中使用return $resultSet-&gt;toArray(); 而不是return $resultSet;。在视图脚本中使用这个$project['alias_name_of_column']
    • 对不起,我收到一个错误 Undefined index: Projectname in C:\xampp\htdocs\...\module\Import\view\import\import\index.phtml on line 33 在我的视图中我像你告诉我的那样使用。输出与 unitcolumns 和每个 projectcolumn 的上述错误相同
    【解决方案2】:

    我认为你没有抓住重点。您不访问操纵表网关的表。您应该做的是使用表网关,这样您就不必再处理表和 SQL。因此模式的名称为Table Gateway。

    看看ZF manual describes this怎么样。

    完成此操作后,很容易在表网关的单一方法后面连接两个表。此方法返回一个完全从数据库概念中删除的模型。

    【讨论】:

    • 你能再解释一下或者举个加盟的例子吗?因为我已经阅读了我能找到的所有内容,但我没有做对。当然我可以在我的控制器中访问我的适配器并从这里运行一个 sql,但我真的很想了解这个 tablegateway 概念。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 2020-07-25
    • 2016-03-11
    • 2017-09-22
    相关资源
    最近更新 更多