Skip to content

Foreign key not set when using create_association magic method? #546

@louismrose

Description

@louismrose

I have the following (MySQL) database schema:

CREATE TABLE `jobs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) DEFAULT NULL,
  `export_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `exports` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `url` VARCHAR(1000) NOT NULL,
PRIMARY KEY (`id`))
  ENGINE = InnoDB DEFAULT CHARSET=utf8;

With the following PHP ActiveRecord models:

class Job extends ActiveRecord\Model {
  // A Job has 0 or 1 Export
  // (but we use belongs to as the foreign key is on the Job table)
  static $belongs_to = [['export']];

  // A Job has a name
  static $attr_accessible = ['name'];
}
class Export extends ActiveRecord\Model {
  // An Export has a URL
  static $attr_accessible = ['url'];
}

When I run the following code, I expected export_id to be the same as Export::last()->id but it is null:

$job = new Job(["name" => "testJob"]);
$job->create_export([
  "url" => "http://www.example.org"
]);
$job->save();
$job->reload();

var_dump($job->export_id);  // prints NULL

Interestingly, $job->name has the correct value (testJob). The MySQL database has the following data:

mysql>  select * from jobs;
+----+---------+-----------+
| id | name    | export_id |
+----+---------+-----------+
|  1 | testJob |      NULL |
+----+---------+-----------+

mysql> select * from exports;
+----+------------------------+
| id | url                    |
+----+------------------------+
|  1 | http://www.example.org |
+----+------------------------+

I've tried the code on both v1.1.2 and the master branch, and am getting the same results on both versions.

Any hints as to what I might be doing wrong? Could this be a bug?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions