Hello,
I have these objects model in my app:
Users Model:
namespace Application\Model;
class Users extends Entity
{
public $id;
public $firstName;
public $lastName;
public $gender;
public function initialize()
{
parent::initialize();
/* Created course by user (Course owner) */
$this->hasMany('id', 'Application\Model\Courses', 'createdBy', array(
'alias' => 'createdCourses',
'foreignKey' => array(
'message' => 'User cannot be deleted because he/she is courses owner in the system'
)
));
/* Teaching course by user */
$this->hasManyToMany(
'id',
'Application\Model\Instructors',
'userId', 'courseId',
'Application\Model\Courses',
'id',
array(
'alias' => 'teachingCourses',
'foreignKey' => array(
'message' => 'User cannot be deleted because he/she has teaching courses in the system'
)
));
}
}
Courses Model:
namespace Application\Model;
class Courses extends Entity
{
public $id;
public $title;
public $createdBy;
public function initialize()
{
parent::initialize();
/* Course creator (Owner) */
$this->belongsTo('id', 'Application\Model\Users', 'createdBy', array(
'alias' => 'creator'
));
/* Course Instructors (Teachers) */
$this->hasManyToMany(
'id',
'Application\Model\Instructors',
'courseId', 'userId',
'Application\Model\Users',
'id',
array(
'alias' => 'instructors'
)
);
}
}
Instructors Model:
namespace Application\Model;
class Instructors extends Base
{
/**
*
* @var integer
*/
public $id;
/**
*
* @var integer
*/
public $userId;
/**
*
* @var integer
*/
public $courseId;
public function initialize()
{
parent::initialize();
$this->belongsTo("userId", 'Application\Model\Users', "id");
$this->belongsTo("courseId", 'Application\Model\Courses', "id");
}
}
In my controller I have create a course then select an existing user from database and assing as course instructor via magic method:
$course = new \Application\Model\Courses();
$course->title = "Sample Title";
.
.
$user = Application\Model\User::findFirst(1);
$course->createdBy = $user->id;
$course->instructors = [$user];
$course->save();
But while saving process, it tries to update that existing user to! Can someone explain what is wrong here.
Thanks.