在belongsPHP 3中的同一个表上有2个belongsTo关联

时间:2015-12-18 18:20:59

标签: cakephp-3.0

我有一个实体,我希望有2个belongsTo关联,而不是1个belongsToMany关联。

所以我想通过agpoitext_id将Orders链接到Agpoitexts,但我也会将订单与AgpoiTexts链接到ref_id,以生成以下sql查询:

感谢下面关于hasMany关联的文档中的示例:

class ArticlesTable extends Table
{

    public function initialize(array $config)
    {
        $this->hasMany('Comments', [
            'className' => 'Comments',
            'conditions' => ['approved' => true]
        ]);

        $this->hasMany('UnapprovedComments', [
            'className' => 'Comments',
            'conditions' => ['approved' => false],
            'propertyName' => 'unapproved_comments'
        ]);
   }
}

我虽然可以通过以下方式成功获得:

class OrdersTable extends Table {

    public function initialize(array $config) {

        $this->belongsTo('Agpoitexts', [
            'dependent' => true,
            'foreignKey' => 'agpoitext_id',
        ]);

        $this->belongsTo('References', [
            'className' => 'Agpoitexts',
            'foreignKey' => 'ref_id',
        ]);

    }
}

但是我得到一个错误,因为Cake生成以下查询并查找references表:

... LEFT JOIN agpoitexts References ON References.id = (Orders.ref_id) LEFT JOIN agpoitexts Agpoitexts ON Agpoitexts.id = (Orders.agpoitext_id) ...

有可能得到我想要的东西吗?

此致

编辑:我得到的错误:

Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'References ON References.id = (Orders.ref_id) LEFT JOIN agpoitexts Agpoitexts ON' at line 1

我想要的是Agpoitexts.id = Orders.ref_id

1 个答案:

答案 0 :(得分:0)

为您的表别名选择的名称是导致您收到错误消息的原因。

Go to the next error: Ctrl + . Go to the previous error: Ctrl + , Show quick fixes: Ctrl + 1 Mac Go to the next error: Cmd + . Go to the previous error: Cmd + , Show quick fixes: Cmd + 1 是MySQL中的一项保留工作。尝试选择不在保留字词列表中的其他单词。

请参阅9.3 Keywords and Reserved Words