php - 在 cakephp 3 中创建适当的关联

标签 php mysql cakephp model cakephp-3.0

我想在两个表之间创建正确的关系。这样,当我从 lease 表获取数据时,我也能够获取 price 表数据。价格表可以有多个lease表id。

表的结构是

租赁表

enter image description here

价格表

enter image description here

其中 lease 表的 id 与价格表的 lease_id 相关。

我尝试使用以下代码但无法获取数据。

class LeasesTable extends Table {

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config) {
        parent::initialize($config);

        $this->table('leases');

        $this->primaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('Offices', [
            'foreignKey' => 'office_type',
            'joinType' => 'INNER'
        ]);
        $this->belongsTo('Countries', [
            'foreignKey' => 'country_id',
            'joinType' => 'INNER'
        ]);
        $this->belongsTo('Areas', [
            'foreignKey' => 'area_id',
            'joinType' => 'INNER'
        ]);
        $this->belongsToMany('id', [
            'foreignKey' => 'lease_id',
            'joinType' => 'INNER',
            'joinTable' => 'Prices',
        ]);
    }

最佳答案

您描述的关联是租赁有许多价格 - 因此您应该在 LeasesTable.php 中使用以下代码:

$this->hasMany("Prices", [
    "foreignKey" => "lease_id"
]);

更多信息:HasMany Associations

关于php - 在 cakephp 3 中创建适当的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45142898/

相关文章:

php - 如何在WordPress中结合meta_query和orderby日期元?

javascript - PHP While 循环中的 jQuery

php删除特定文件夹及其所有内容

php - 通过权限位掩码从 MySQL 数据库中选择用户?

mysql - 缩小不断增长的时间相关 Mysql 表的大小

MySQL:如何使用 ODBC 获取表中的字段列表

mysql - 将 Perl 中的字符串拆分到数据库中

Cakephp 2.0 + 元素 + requestAction = 空结果

cakephp - 如何访问 PagesController 中的模型——或者如何使用 CakePHP 创建仪表板

mysql - CakePHP 将值作为 HTML 编码值保存到 MySQL 数据库