【问题标题】:How to Join one table to another table by zipcode?如何通过邮政编码将一张桌子连接到另一张桌子?
【发布时间】:2015-06-09 10:07:05
【问题描述】:

我有两张桌子我想加入Ad.zipcodeZipcode.zip 请查看以下详细信息 -

表格:广告

+----+----------+---------+----------+
| id | user_id  | zipcode |  photo   |
+----+----------+---------+----------+
|  1 | 1        | 751010  | img1.jpg |
|  2 | 2        | 123456  | img2.jpg |
|  3 | 3        | 756114  | img3.jpg |
|  4 | 4        | 121010  | img4.jpg |
|  5 | 5        | 789520  | img5.jpg |
|  6 | 6        | 404040  | img6.jpg |
|  7 | 7        | 805020  | img7.jpg |
+----+----------+---------+----------+

表格:邮政编码

+--------+---------+----------+
|  zip   | city    |  state   |
+--------+---------+----------+
| 789520 | ctc     | odisha   |
| 756114 | bhadrak | odisha   |
| 123456 | bbsr    | odisha   |
| 756114 | rlc     | odisha   |
| 789502 | bls     | odisha   |
---------+---------+----------+

我想加入ads 表中包含的邮​​政编码,我需要获取第二个表中ads zipcode756114 的记录

我已尝试加入$hasMany,但zipcodes 表中不存在id,为什么加入不起作用。

我的代码:

public $hasMany = array(
    'Zipcode' => array(
        'className' => 'Zipcode',
        'foreignKey' => 'zip',
    ),
);

在我上面的代码中,我得到了空白数组。请帮我。 嗨,我使用的是 CakePHP version-2.x

如何将模型与另一个模型关联?

【问题讨论】:

    标签: mysql cakephp-2.0 model-associations


    【解决方案1】:

    在您的邮政编码模型中,您需要:

    public $primaryKey = 'zip';
    

    顺便说一句,为什么您在该表中没有自动数字 PK?邮政编码通常包含非数字字符...

    【讨论】:

      【解决方案2】:

      在广告模型位置:

      public $belongsTo = array(
          'Zipcode' => array(
              'className' => 'Zipcode',
              'foreignKey' => 'zipcode',
          )
      );
      

      在邮政编码模型的地方:

      public $primaryKey = 'zip';
      
      public $hasMany = array(
          'Ad' => array(
              'className' => 'Ad',
              'foreignKey' => 'zipcode',
          )
      );
      

      【讨论】:

      • zip 可以包含重复值。如何在主键中设置?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-24
      • 1970-01-01
      • 1970-01-01
      • 2014-10-14
      • 2011-10-09
      • 2020-07-29
      • 2015-11-28
      相关资源
      最近更新 更多