这个问题在stackoverflow上被多次询问,但没有一个帮助过我。
我有3张桌子:
student
subject
student_subject
问题:当我尝试插入数据时,行会插入到student
和subject
表中,但不会插入到student_subject
表中。
环境保护:
数据库模式上的详细信息:我的表结构是:
student_subject
表:
mysql> desc student_subject;
+------------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| student_id | int(11) | YES | MUL | NULL | |
| subject_id | int(11) | YES | MUL | NULL | |
+------------+---------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
subject
表:
mysql> desc student;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| class | char(1) | YES | | NULL | |
+-------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
subject
表:
mysql> desc subject;
+--------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| author | varchar(255) | YES | | NULL | |
+--------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
PHP上的详细信息(CodeIgniter)代码:
C:\xampp\htdocs\test_orm\application\libraries\doctrine.php
:
<?php
use Doctrine\Common\ClassLoader,
Doctrine\ORM\Configuration,
Doctrine\ORM\EntityManager,
Doctrine\Common\Cache\ArrayCache,
Doctrine\DBAL\Logging\EchoSQLLogger,
Doctrine\ORM\Mapping\Driver\DatabaseDriver,
Doctrine\ORM\Tools\DisconnectedClassMetadataFactory,
Doctrine\ORM\Tools\EntityGenerator;
/**
* CodeIgniter Smarty Class
*
* initializes basic doctrine settings and act as doctrine object
*
* @final Doctrine
* @category Libraries
*/
class Doctrine {
/**
* @var EntityManager $em
*/
public $em = null;
/**
* constructor
*/
public function __construct()
{
// load database configuration from CodeIgniter
require APPPATH.'config/database.php';
// Set up class loading. You could use different autoloaders, provided by your favorite framework,
// if you want to.
require_once APPPATH.'third_party/Doctrine/Common/ClassLoader.php';
$doctrineClassLoader = new ClassLoader('Doctrine', APPPATH.'third_party');
$doctrineClassLoader->register();
$entitiesClassLoader = new ClassLoader('models', rtrim(APPPATH, "/" ));
$entitiesClassLoader->register();
$proxiesClassLoader = new ClassLoader('proxies', APPPATH.'models');
$proxiesClassLoader->register();
// Set up caches
$config = new Configuration;
$cache = new ArrayCache;
$config->setMetadataCacheImpl($cache);
$driverImpl = $config->newDefaultAnnotationDriver(array(APPPATH.'models/Entities'));
$config->setMetadataDriverImpl($driverImpl);
$config->setQueryCacheImpl($cache);
// Proxy configuration
$config->setProxyDir(APPPATH.'models/proxies');
$config->setProxyNamespace('Proxies');
// Set up logger
//$logger = new EchoSQLLogger;
//$config->setSQLLogger($logger);
$config->setAutoGenerateProxyClasses( TRUE );
// Database connection information
$connectionOptions = array(
'driver' => 'pdo_mysql',
'user' => $db['default']['username'],
'password' => $db['default']['password'],
'host' => $db['default']['hostname'],
'dbname' => $db['default']['database']
);
// Create EntityManager
$this->em = EntityManager::create($connectionOptions, $config);
$this->em->getConfiguration()
->setMetadataDriverImpl(
new DatabaseDriver(
$this->em->getConnection()->getSchemaManager()
)
);
//$this->generate_classes();
}
/**
* generate entity objects automatically from mysql db tables
* @return none
*/
function generate_classes(){
$cmf = new DisconnectedClassMetadataFactory();
$cmf->setEntityManager($this->em);
$metadata = $cmf->getAllMetadata();
$generator = new EntityGenerator();
$generator->setUpdateEntityIfExists(true);
$generator->setGenerateStubMethods(true);
$generator->setGenerateAnnotations(true);
$generator->generate($metadata, APPPATH."models/Entities");
}
}
C:\xampp\htdocs\test_orm\application\models\Entities\Subject.php
<?php
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Subject
*
* @ORM\Table(name="subject")
* @ORM\Entity
*/
class Subject
{
public function __construct() {
$this->students = new ArrayCollection();
}
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255, nullable=true)
*/
private $name;
/**
* @var string
*
* @ORM\Column(name="author", type="string", length=255, nullable=true)
*/
private $author;
/**
* @ORM\ManyToMany(targetEntity="Student" mappedBy="subjects")
*/
protected $students;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
* @return Subject
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set author
*
* @param string $author
* @return Subject
*/
public function setAuthor($author)
{
$this->author = $author;
return $this;
}
/**
* Get author
*
* @return string
*/
public function getAuthor()
{
return $this->author;
}
/**
* Add the Student to Subject
*
* @param Student $student
* @return void
*/
public function addStudent(Student $student){
$student->addSubject($this);
$this->students[] =$student;
}
public function getStudents () {
return $this->students;
}
}
C:\xampp\htdocs\test_orm\application\models\Entities\Student.php
<?php
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Student
*
* @ORM\Table(name="student")
* @ORM\Entity
*/
class Student
{
public function __construct() {
$this->subjects = new ArrayCollection();
}
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255, nullable=true)
*/
private $name;
/**
* @var string
*
* @ORM\Column(name="class", type="string", length=1, nullable=true)
*/
private $class;
/**
* @ORM\ManyToMany(targetEntity="Subject", inversedBy="students")
* @ORM\JoinTable(name="student_subject")
*/
protected $subjects;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
* @return Student
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set class
*
* @param string $class
* @return Student
*/
public function setClass($class)
{
$this->class = $class;
return $this;
}
/**
* Get class
*
* @return string
*/
public function getClass()
{
return $this->class;
}
/**
* Add the Subject to Student
*
* @param Subject $subject
* @return void
*/
public function addSubject(Subject $subject){
//$subject->addStudent($this);
$this->subjects[] = $subject;
}
public function getSubjects () {
return $this->subjects;
}
}
C:\xampp\htdocs\test_orm\application\models\StudentModel.php
<?php
require_once(APPPATH."models/Entities/Student.php");
require_once(APPPATH."models/Entities/Subject.php");
//use Doctrine\ORM\EntityManager;
use \Student;
use \Subject;
class StudentModel extends CI_Model {
/**
* @var \Doctrine\ORM\EntityManager $em
*/
var $em;
public function __construct() {
parent::__construct();
$this->em = $this->doctrine->em;
}
/**
* Add contact messages to database
* @param array $contact_form
* @return bool
*/
public function addSubject()
{
/**
* @var Student $student
*/
$student = new Student();
$student->setName("Musa Haidari");
$student->setClass("BCS");
$subject = new Subject();
$subject->setName("JAVA");
$subject->setAuthor("XXX");
$this->em->persist($subject);
$subject = new Subject();
$subject->setName("PHP");
$subject->setAuthor("YYY");
$this->em->persist($subject);
$student->addSubject($subject);
$this->em->persist($student);
try {
//save to database
$this->em->flush();
}
catch(Exception $err){
die($err->getMessage());
}
return true;
}
}
C:\xampp\htdocs\test_orm\application\controllers\Landing.php
类着陆扩展了CI_Controller {
public function index()
{
$this->load->view('welcome_message');
}
public function addStudentSubjectLog () {
$this->load->model('StudentModel');
$this->StudentModel->addSubject();
echo "<br /><br />Done!<br /><br />";
}
}
要插入数据,我在浏览器中输入此URL:
http://localhost/test_orm/Landing/addStudentSubjectLog
答案 0 :(得分:0)
我认为您应该从//$subject->addStudent($this);
实体的addSubject
函数中取消注释Student
行。
另外,从您$student->addSubject($this);
实体的addStudent
函数中删除行Subject
。
我认为在向$student
添加$subject
之前,您还应该保留$student->addSubject($subject);
$this->em->persist($student);
对象。基本上切换这两行:
$scope.myObject
希望这有帮助。