Reputation: 915
Hi I coudln't get Cortex hasMany to hasMany relation working so I made a simple test. I created two classes, CortexTestA and CortexTestB in my models namespace
namespace models;
use DB\Cortex;
class CortexTestA extends Cortex {
protected $fieldConf = array(
'name' => array(
'type' => 'VARCHAR256',
'nullable' => false
),
'cortextestb' => array(
'has-many' => array('models\CortexTestB', 'cortextesta', 'cortextest_a_b')
)
);
// constructor etc. follows
This is the field conf for CortexTestB:
'cortextesta' => array(
'has-many' => array('models\CortexTestA', 'cortextestb', 'cortextest_a_b')
)
Next I ran the setup command
\Models\CortexTestA::setup();
\Models\CortexTestB::setup();
But already something strange happens, both tables now have obsolete fields:
CREATE TABLE IF NOT EXISTS `cortextesta` (
`id` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`cortextestb` int(11) DEFAULT NULL
)
CREATE TABLE IF NOT EXISTS `cortextestb` (
`id` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`cortextesta` int(11) DEFAULT NULL
)
The m2m table does get created correctly though:
CREATE TABLE IF NOT EXISTS `cortextest_a_b` (
`id` int(11) NOT NULL,
`cortextesta` int(11) DEFAULT NULL,
`cortextestb` int(11) DEFAULT NULL
)
But now when I run this
$cta = new \models\CortexTestA();
$cta->name = "SomethingA";
$cta->save();
// Results in: INSERT INTO `cortextesta` (`id`, `name`, `cortextestb`) VALUES
// (1, 'SomthingA', NULL);
and then this:
$cta = new \models\CortexTestA();
$cta->load(array('id = ?', 1));
$ctb = new \models\CortexTestB();
$ctb->name = "SomethingB";
$ctb->cortextesta[] = $cta;
$ctb->save();
the relationship table cortextest_a_b remains empty. What am I doing wrong?
Upvotes: 0
Views: 104
Reputation: 2052
When the relation is still empty, the property getter currently returns NULL
. That's why the array modification unfortunately doesn't work. You can easily workaround that like this:
if (!$ctb->cortextesta)
$ctb->cortextesta = array($cta);
else
$ctb->cortextesta[] = $cta;
$ctb->save();
I'll see if I can optimized this a bit. The issue about the obsolete fields is indeed a bug. I'll patch that soon. thanks.
Upvotes: 1