繁体   English   中英

消息:SQLSTATE [42S22]:找不到列:1054“字段列表”中的未知列“ t0._firstName”

[英]Message: SQLSTATE[42S22]: Column not found: 1054 Unknown column 't0._firstName' in 'field list'

我有将模块zend Framework 1.12放入模块2中的Web应用程序(我只需要这样),现在我正尝试从数据库中获取数据,并在我点击正确的url时回显json_encode url / api / people(将返回所有人员)。

出于某种原因,我遇到此错误,告诉我t0._firstName为列,但我知道它根本不是列。 我确实在控制器中使用_firstName作为变量。

- - -堆栈跟踪 - - -

#0 /var/www/app/library/Doctrine/DBAL/Connection.php(633): PDO->query('SELECT t0.id AS...')
#1 /var/www/app/library/Doctrine/ORM/Persisters/BasicEntityPersister.php(727): Doctrine\DBAL\Connection->executeQuery('SELECT t0.id AS...', Array, Array)
#2 /var/www/app/library/Doctrine/ORM/EntityRepository.php(179): Doctrine\ORM\Persisters\BasicEntityPersister->loadAll(Array, NULL, NULL, NULL)
#3 /var/www/app/library/Doctrine/ORM/EntityRepository.php(165): Doctrine\ORM\EntityRepository->findBy(Array)
#4 /var/www/app/application/modules/api/controllers/PeopleController.php(19): Doctrine\ORM\EntityRepository->findAll()
#5 /var/www/app/library/Zend/Controller/Action.php(516): API_PeopleController->indexAction()
#6 /var/www/app/library/Zend/Controller/Dispatcher/Standard.php(308): Zend_Controller_Action->dispatch('indexAction')
#7 /var/www/app/library/Zend/Controller/Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#8 /var/www/app/library/Zend/Application/Bootstrap/Bootstrap.php(97): Zend_Controller_Front->dispatch()
#9 /var/www/app/library/Zend/Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#10 /var/www/app/public/index.php(79): Zend_Application->run()
#11 {main}

----- PeopleController -----

    <?php

use Doctrine\ORM;
use API\Entity;

class API_PeopleController extends Ia_Controller_Action_Abstract
{
  public function indexAction()
  {
      if($this->getRequest()->isGet())
      {
        //access class
        $peopleClass = new API\Entity\People;
        //get entityManager
        $em = $peopleClass->getEntityManager();
        //get repo
        $peopleRepo = $em->getRepository('API\Entity\People');
        //use function from repo
        $people = $peopleRepo->findAll();
        foreach ($people as $obj)
        {
          echo $people;
        }
        //try to display all objects.
        /*
        foreach($people as $obj)
        {
          $resultArray[] = 
          [
            'id'         => $obj->id,
            'firstname'  => $obj->firstname,
            'lastname'   => $obj->lastname,
            "food"       => $obj->food
          ];
        }
        echo json_encode($resultArray, JSON_PRETTY_PRINT);
        */


        //$peopleMapper = new API_Model_PeopleMapper();
        //$this->view->entries = $peopleMapper->fetchAll();
      }
      else if($this->getRequest()->isPost())
      {
          $request = $this->getRequest();
          $getPeopleValues = $request->getPost();
          $people = new API_Model_People();

          $firstName = $getPeopleValues['firstName'];
          $lastName = $getPeopleValues['lastName'];
          $favFood = $getPeopleValues['favoriteFood'];

          if(empty($firstName) || empty($lastName) || empty($favFood))
          {
            throw new Exception("Please fill out all inputs", 1);
          }

          $people   ->setFirstName($firstName)
                    ->setLastName($lastName)
                    ->setFavoriteFood($favFood);
          $peopleMapper = new API_Model_PeopleMapper();
          $peopleMapper->save($people);
      }
      else
      {
        throw new Exception("Error: Get/Post didn't work and something went really wrong", 1);
      }
  }

  public function getAction()
  {
      $people = new API_Model_People();
      $peopleMapper = new API_Model_PeopleMapper();
      $request = $this->getRequest();
      $id = $request->getParam('peopleId');
      $this->view->entries = $peopleMapper->getPeopleVisits($id);
  }
}

?>

----- People.php -----

    <?php

namespace API\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\EntityRepository;
/**
*
* @ORM\Table(name="People")
* @ORM\HasLifecycleCallbacks
* @ORM\Entity(repositoryClass="API\Entity\PeopleRepository")
* @author Paul Chu <paulchu756@gmail.com>
*/
class People
{
    /**
    *
    * @var integer $id
    * @ORM\Column(name="id", type="integer", nullable=false)
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="IDENTITY")
    */
    protected $_id;

    /**
    *
    * @var string
    * @ORM\Column(name="firstname", type="string", length=60, nullable=false)
    */
    protected $_firstName;

    /**
    *
    * @var string
    * @ORM\Column(name="lastname", type="string", length=60, nullable=false)
    */
    protected $_lastName;

    /**
    *
    * @var string
    * @ORM\Column(name="food", type="string", length=60, nullable=false)
    */
    protected $_favoriteFood;


    public function setId($id)
    {
        $this->_id = (int) $id;
        return $this;
    }
    public function getId()
    {
        return $this->_id;
    }

    public function setFirstName($firstName)
    {
        $this->_firstName = (string) $firstName;
        return $this;
    }
    public function getFirstName()
    {
        return $this->_firstName;
    }

    public function setLastName($lastName)
    {
        $this->_lastName = (string) $lastName;
        return $this;
    }
    public function getLastName()
    {
        return $this->_lastName;
    }

    public function setFavoriteFood($favoriteFood)
    {
        $this->_favoriteFood = (string) $favoriteFood;
        return $this;
    }
    public function getFavoriteFood()
    {
        return $this->_favoriteFood;
    }


    public function __construct(array $options = null)
    {
        if(is_array($options))
        {
            $this->setOptions($options);
        }
    }

    public function setOptions(array $options)
    {
        $methods = get_class_methods($this);
        foreach($options as $key => $value)
        {
            $method = 'set' . ucfirst($key);
            if(in_array($method, $methods))
            {
                $this->$method($value);
            }
        }
        return $this;
    }

    /**
    *
    * \Doctrine\Entity\Manager
    */
    public $em = null;

    /**
    * Get Doctrine Entity Manager
    * @return \Doctrine\Entity\Manager
    */
    public function getEntityManager() {
        if($this->em===null){
            $dc = \Zend_Registry::get('doctrine');
            $this->em = $dc->getEntityManager();
        }
        return $this->em;
    }

    /**
    * Magic getter to expose protected properties.
    *
    * @param string $property
    * @return mixed
    */
    public function __get($property) {
        return $this->$property;
    }

    /**
    * Magic setter to save protected properties.
    *
    * @param string $property
    * @param mixed $value
    */
    public function __set($property, $value) {
        $this->$property = $value;
    }

    /**
    * Convert the object to an array.
    *
    * @return array
    */
    public function toArray() {
        $vars = get_object_vars($this);
        return $vars;
    }

    /**
    * Create an entity with the given data
    *
    * @param array $data
    * @return object
    */
    public function createEntity(array $data)
    {
        $metadata = $this->getEntityManager()->getClassMetadata(get_class($this));
        if(isset($data['id'])){
            $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE);
        }
        $entity = $metadata->newInstance();
        return $this->updateEntity($entity,$data);
    }

    /**
    * Update an entity with the given data
    *
    * @param array $data
    * @return object
    */
    public function updateEntity($entity, array $data)
    {
        $metadata = $this->getEntityManager()->getClassMetadata(get_class($this));
        foreach($data as $property => $value){
            if(!$metadata->reflClass->hasProperty($property))
                continue;
            $metadata->setFieldValue($entity, $property, $value);
        }
        return $entity;
    }

    /** @ORM\PrePersist */
    public function prePersist()
    {
        $this->created_at = new \DateTime;
        $this->updated_at = new \DateTime;
    }

    /** @ORM\PreUpdate */
    public function preUpdate()
    {
        $this->updated_at = new \DateTime;
    }

}

------ init.php(数据库)------

    <?php
//zf configure db-adapter "adapter=PDO_MYSQL&dbname=[myDB]&host=[localhost]&username=[root]&password=[root]" -s development
// Define variables.
$host = "localhost";
$user = "root";
$password = "root";
$database = "myDB";

//Create connection
$connection = mysqli_connect($host, $user, $password);
// Check connection
if(!$connection){
die("Could not connect: " . mysqli_connect_error());}
else{
    echo "Connection successfully \n";
}

// Drop database
/*
$dropDB = "DROP DATABASE myDB";
// Check drop database
if($connection->query($dropDB) === TRUE){
    echo "Database myDB was successfully dropped \n";
} else {
    echo "Error dropping database: \n" . $connection->error;
}
*/

//Create Database called "myDB"
$db = "CREATE DATABASE IF NOT EXISTS myDB";
//Check Datebase
if($connection->query($db) === TRUE){
    echo "Database created successfully \n";
} else {
    echo "Error creating database: \n" . $connection->error;
}

// Select Database
$connection->select_db($database);

// Drop Visits table;
$dropVisitsTable = "DROP TABLE Visits";
if($connection->query($dropVisitsTable) === TRUE){
    echo "Visits Table was successfully dropped \n";
} else {
    echo "Error dropping visits table: " . $connection->error . "\n";
}

// Drop People table;
$dropPeopleTable = "DROP TABLE People";
if($connection->query($dropPeopleTable) === TRUE){
    echo "People Table was successfully dropped \n";
} else {
    echo "Error dropping people table: " . $connection->error . "\n";
}

// Drop States table;
$dropStatesTable = "DROP TABLE States";
if($connection->query($dropStatesTable) === TRUE){
    echo "States Table was successfully dropped \n";
} else {
    echo "Error dropping states table: " . $connection->error . "\n";
}

// Create People Table
$peopleTable = "CREATE TABLE IF NOT EXISTS People
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
firstname varchar(40) NOT NULL,
lastname varchar(40) NOT NULL,
food varchar(40) NOT NULL
)";

//Create States Table
$statesTable = "CREATE TABLE IF NOT EXISTS States
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
stateabb varchar(2) NOT NULL,
statename varchar(40) NOT NULL
)";

// Create Visit Table
$visitTable = "CREATE TABLE IF NOT EXISTS Visits
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
p_id INT(40) NOT NULL,
s_id INT(40) NOT NULL,
FOREIGN KEY (p_id) REFERENCES People(id),
FOREIGN KEY (s_id) REFERENCES States(id),
date_visited varchar(40) NOT NULL
)";

//Check States Table
if($connection->query($statesTable) === TRUE)
{
    echo "States Table created successfully \n";
}
else
{
    echo "States Table wasn't created \n" . $connection->error;
}
//Check People Table
if($connection->query($peopleTable) === TRUE)
{
    echo "People Table created successfully \n";
}
else
{
    echo "People Table wasn't created \n" . $connection->error;
}
//Check Visit Table
if($connection->query($visitTable) === TRUE)
{
    echo "Visit Table created successfully \n";
}
else
{
    echo "Visit Table wasn't created \n" . $connection->error;
}

// Insert data into states table
$insertData = " INSERT INTO States (stateabb, statename)
                VALUES ('LA', 'Louisiana');";
$insertData .= "INSERT INTO States (stateabb, statename)
                VALUES ('FL', 'Florida');";
$insertData .= "INSERT INTO States (stateabb, statename)
                VALUES ('TX', 'Texas');";
$insertData .= "INSERT INTO States (stateabb, statename)
                VALUES ('NM', 'New Mexico');";
$insertData .= "INSERT INTO States (stateabb, statename)
                VALUES ('ID', 'Idaho');";
$insertData .= "INSERT INTO States (stateabb, statename)
                VALUES ('IA', 'Iowa');";
$insertData .= "INSERT INTO States (stateabb, statename)
                VALUES ('ME', 'Maine');";
$insertData .= "INSERT INTO States (stateabb, statename)
                VALUES ('NV', 'Nevada');";
$insertData .= "INSERT INTO States (stateabb, statename)
                VALUES ('NY', 'New York');";
$insertData .= "INSERT INTO States (stateabb, statename)
                VALUES ('UT', 'Utah');";

// Insert data into people table
$insertData .= "INSERT INTO People (firstname, lastname, food)
                VALUES ('Paul', 'Chu', 'Rice');";
$insertData .= "INSERT INTO People (firstname, lastname, food)
                VALUES ('Chui', 'Chu', 'Steak');";
$insertData .= "INSERT INTO People (firstname, lastname, food)
                VALUES ('Pandalord', 'Chu', 'Cookies');";
$insertData .= "INSERT INTO People (firstname, lastname, food)
                VALUES ('LordBabyPanda', 'Chu', 'Milk');";

// Insert data into Visits table
$insertData .= "INSERT INTO Visits (p_id, s_id, date_visited)
                VALUES ('1', '1', '1994/07/14');";
$insertData .= "INSERT INTO Visits (p_id, s_id, date_visited)
                VALUES ('1', '2', '1994/07/14');";
$insertData .= "INSERT INTO Visits (p_id, s_id, date_visited)
                VALUES ('2', '10', '1994/07/14');";
$insertData .= "INSERT INTO Visits (p_id, s_id, date_visited)
                VALUES ('3', '9', '1994/07/14');";
$insertData .= "INSERT INTO Visits (p_id, s_id, date_visited)
                VALUES ('4', '7', '1994/07/14');";

// Check stateData in table
if($connection->multi_query($insertData) === TRUE)
{
    $lastID = $connection->insert_id;
    echo "insertData create successfully. Last inserted ID is: " . $lastID . "\n";
}
else
{
    echo "Error: \n" . $connection->error;
}
//Close Connection
$connection->close();
?>

如果您使用它来获取对象的属性:

$resultArray[] = 
          [
            'id'         => $obj->id,
            'firstname'  => $obj->firstname,
            'lastname'   => $obj->lastname,
            "food"       => $obj->food
          ];

您无法直接获取属性,因为其中有受保护的属性,您必须使用已实现的方法,例如:

            'firstname'  => $obj->getFirstname(),

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM