我有这个模块web应用程序,它是zend框架1.12到doctrine 2(我只需要这样),现在我正试图从我的数据库中获取数据并在我点击时回显json_encode正确的url是url / api / people(将返回所有人)。
由于某种原因,我有这个错误告诉我t0._firstName作为一列,但我知道它根本不是一个列。我在控制器中使用_firstName作为变量。
----- stacktrace -----
#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();
?>
答案 0 :(得分:2)
如果您使用它来获取对象的属性:
$resultArray[] =
[
'id' => $obj->id,
'firstname' => $obj->firstname,
'lastname' => $obj->lastname,
"food" => $obj->food
];
您无法直接获取属性,因为受保护,您必须使用以下实现的方法:
'firstname' => $obj->getFirstname(),