CakePHP 3.x-保存在关联表中不起作用

时间:2019-06-28 06:28:29

标签: cakephp-3.7

我有下面的表格结构。

Mantator表

class MandatorTable extends Table
{
public function initialize(array $config)
    {
        $this->table('mandators');

        $this->belongsToMany('Seminar', [
            'foreignKey' => 'mandator_id',
            'targetForeignKey' => 'seminar_id',
            'joinTable' => 'mandators_seminars'
        ]);
    }
}

Semiar表

class SeminarTable extends Table
{
    public function initialize(array $config)
    {
        $this->table('seminars');

        $this->belongsToMany('Mandator', [
            'foreignKey' => 'seminar_id',
            'targetForeignKey' => 'mandator_id',
            'joinTable' => 'mandators_seminars'
        ]); 
    }   
}

两个表都属于“ mandators_seminars”表

mandator_id,workshop_id

当我保存数据时,它将保存在研讨会表中,而不是在“ mandators_seminars”表中

查询

$seminartable = $this->Seminar->newEntity();

$this->request->data['mandator'][0] = 1;

$seminardata = $this->Seminar->patchEntity($seminartable, $this->request->data);
$this->Seminar->save($seminardata)

请求数据

Array
(
    [bookable] => test
    [released] => aaa
    [linkable] => bb
    [name] => ccc
    [internalnote] => ddd
    [abstract] => ttt
    [description] => ddd
    [Category] => 14
    [mandator] => Array
        (
            [0] => 1
        )

    [mandator_owner_id] => 1
)

1 个答案:

答案 0 :(得分:0)

看起来您有两个表Mandator和类似的单数,但是您的连接表是复数的。首先检查一下。如果仍然有问题,请检查此CakePHP Through Association

如您所见,您的关联应如下所示:

$this->belongsToMany('Mandator', [
        'foreignKey' => 'seminar_id',
        'targetForeignKey' => 'mandator_id',
        'through' => 'PluginName.MandatorsSeminars'
        'joinTable' => 'mandators_seminars',
        'className' => 'PluginName.Mandator'
    ]); 

还有一个提示:表格应称为复数形式。