【发布时间】:2018-10-01 11:39:00
【问题描述】:
我正在使用 php,我有两个实体 Message 和 Post。帖子是消息实体中的一个属性,它应该是一对一的单向关系。但是当我在控制器中调用 message->getPost()->getText() 时,我收到以下错误消息:
试图在 C:\wamp64\www\Test\monApplication\controller\mainController.php 中获取非对象的属性
消息实体:
<?php
/**
* @Entity
* @Table(name="message")
*/
class message{
/** @Id @Column(type="integer")
* @GeneratedValue
*/
public $id;
/**
* @ORM\OneToOne(targetEntity="post", cascade={"persist"})
* @JoinColumn(name="post", referencedColumnName ="id")
*/
private $post;
/** @Column(type="integer") */
public $likes;
public function getPost(){
return $this->post;
}
public function getLikes(){
return $this->likes;
}
}
?>
帖子实体
<?php
/**
* @Entity
* @Table(name="post")
*/
class post{
/** @Id @Column(type="integer")
* @GeneratedValue
*/
public $id;
/** @Column(type="string", length=2000) */
public $texte;
/** @Column(type="string", length=200) */
public $image;
/** @Column(type="TIMESTAMP", length=4000) */
public $date;
}
?>
我的 dbconnection 类:
<?php
define ('HOST', 'localhost') ;
define ('USER', 'root' ) ;
define ('PASS', '' ) ;
define ('DB', 'tp' ) ;
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
class dbconnection{
private static $instance=null, $entityManager;
private $error=null ;
private function __construct(){
$config = Setup::createAnnotationMetadataConfiguration(array("../../monApplication/model/"), true);
$param = array(
'dbname' => DB,
'user' => USER,
'password' => PASS,
'host' => HOST,
'driver' => 'pdo_mysql');
try{
self::$entityManager = EntityManager::create($param, $config);
}
catch(Exception $e) {
echo "Probleme connexion base de données:".$e->getMessage();
$this->error = $e->getMessage();
}
}
public static function getInstance(){
if(self::$instance == null){
self::$instance = new dbconnection();
}
return self::$instance;
}
public function closeConnection(){
self::$instance=null;
}
public function getEntityManager(){
if(!empty(self::$entityManager))
return self::$entityManager;
else
return NULL;
}
public function __clone(){
}
public function getError(){
return $this->error;
}
}
我的主控制器:
<?php
class mainController
{
public static function showMessage($request,$context){
$messages = messageTable::getAllMessages();
echo $message[0]->getPost()->text;
return context::SUCCESS;
}
}
最后我的项目架构是这样的:
【问题讨论】:
-
我在您的代码中看不到
$message->getPost()被调用的位置?我希望这是在mainController.php,您没有显示。无论如何,造成这种情况的原因很可能是变量$message不包含对象。也许它是空的? -
我刚刚将我的 mainController 类添加到问题中,$message 对象不是空的,因为 getLikes() 工作正常
-
嗯,我猜这需要调试。
$message[0]有什么东西吗?它是什么类型的? -
我在提供的代码中没有看到命名空间和使用指令。请确保您使用正确的命名空间并包含正确的类。
-
您的消息表上的连接列是名为“post”还是可能是“post_id”?尝试运行验证命令doctrine-project.org/projects/doctrine-orm/en/2.6/reference/… 并检查架构中的错误。
标签: php doctrine-orm orm doctrine entity