在本书的例子中:
https://book.cakephp.org/3.0/en/orm/associations.html#using-the-through-option
class StudentsTable extends Table
{
public function initialize(array $config)
{
$this->belongsToMany('Courses', [
'through' => 'CoursesMemberships',
]);
}
}
class CoursesTable extends Table
{
public function initialize(array $config)
{
$this->belongsToMany('Students', [
'through' => 'CoursesMemberships',
]);
}
}
class CoursesMembershipsTable extends Table
{
public function initialize(array $config)
{
$this->belongsTo('Students');
$this->belongsTo('Courses');
}
}
我想在添加新grade
时输入与课程#8相对应的student
。我遵循以下两个例子:
https://book.cakephp.org/3.0/en/orm/saving-data.html#saving-belongstomany-associations
和
https://book.cakephp.org/3.0/en/views/helpers/form.html#associated-form-inputs
并修改add
StudentsController.php
方法
public function add()
{
$student = $this->Students->newEntity();
if ($this->request->is('post')) {
$student = $this->Students->patchEntity($user, $this->request->getData(), [
'associated' => [
'Courses']]);
if ($this->Students->save($student,['associated' => ['Courses._joinData']])) {
$this->Flash->success(__('The student has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The student could not be saved. Please, try again.'));
}
$courses = $this->Students->Courses->find('list', ['limit' => 200]);
$this->set(compact('student', 'courses'));
$this->set('_serialize', ['student']);
}
和Students/add.ctp
echo $this->Form->control('courses._ids', ['options' => $courses]);
echo $this->Form->control('courses.5._joinData.grade');
当我在视图中选择课程#8并输入相应的成绩时,我在CoursesMemberships
表格中看不到它。它会添加记录本身,但grade
不存在。
答案 0 :(得分:1)
您不能将特殊_ids
语法和传统语法混合用于表达嵌套数据结构,即property.index.field...
(有关该行为的文档中的注释可能不会受到影响)。
同样在索引5
添加数据似乎非常随意,您要添加新的链接/记录,因此通常从0
开始。
抛弃_ids
语法并通过明确定义其主键来构建正确的课程数据集,如:
echo $this->Form->control('courses.0.id', ['type' => 'select', 'options' => $courses]);
echo $this->Form->control('courses.0._joinData.grade');
另见
答案 1 :(得分:0)
起初我没有在你的添加功能中看到$ course ...
也许如果您将网站更改为$ courses
$ items = $ this-> Students-> Courses-> find('list',['limit'=> 200]);
或在您看来:
echo $this->Form->control('courses._ids', ['options' => $items]);