关于mysql:如何定义与cakePHP的关系? | 珊瑚贝

How to define relations with cakePHP?


我已经阅读过关于对流的文章,并且我的应用程序/数据库是直接的。

我也读过关于 $hasOne、$hasMany、$belongsTo 等的文章

但是,我正面临一个我无法为自己解决的问题/问题。

我的模型:汽车、活动、加油、维修
我的控制器: CarsController

我的关系:

1
2
3
4
class Car extends AppModel {
    public $BelongsTo = array(‘User’);
    public $hasMany = array(‘Event’);
}

.

1
2
3
4
class Event extends AppModel {
    public $BelongsTo = array(‘Car’);
    public $hasOne = array(‘Refuel’);
}

.

1
2
3
class Refuel extends AppModel {
    public $BelongsTo = array(‘Event’);
}

从 CarsController 执行的 find() 的输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
array(
    ‘Car’ => array(
        ‘id’ => ‘1’,
        ‘user_id’ => ‘1’,
        ‘make’ => ‘Make’,
        ‘model’ => ‘Model’,
    ),
    ‘Event’ => array(
        (int) 0 => array(
            ‘id’ => ‘1’,
            ‘car_id’ => ‘1’,
            ‘dateEvent’ => ’20-10-2014′,
            ‘description’ => ‘1’
        ),
        (int) 1 => array(
            ‘id’ => ‘2’,
            ‘car_id’ => ‘1’,
            ‘dateEvent’ => ’20-10-2014′,
            ‘description’ => ‘2’
        ),
        (int) 2 => array(
            ‘id’ => ‘3’,
            ‘car_id’ => ‘1’,
            ‘dateEvent’ => ’20-10-2014′,
            ‘description’ => ‘3’
        )
    )
)

你需要知道:
汽车属于用户。用户可能有很多辆车
车上有很多活动。一个活动只有一辆车。
每个事件都应与一次加油或一次维修相关联。一次加油或维修不能关联多个事件。

表格:

用户:id
汽车:id,user_id
事件:id,car_id
加油:id,event_id(唯一)
修复:id,event_id(唯一)

  • 我是否很好地定义了关系?
  • cakePHP、特殊事件-加油和事件-修复如何表达?
    • 您能解释一下您遇到的问题或疑问吗?你已经提供了很多很好的数据,但是 – 不确定你在问什么。


    你错过了

    1
    2
    3
    class User extends AppModel {
        public $hasMany = array(‘Car’);
    }

    我发现 array(‘recursive’ => 2) 解决了这个问题!

    但是这是什么,为什么?

    • book.cakephp.org/2.0/en/models/model-attributes.html#recursi??ve, book.cakephp.org/2.0/en/core-libraries/behaviors/…
    • 递归 2 不好。不要使用它。请改用可包含的。不过好消息是,如果将 recursive 设置为 2 可以获得所需的数据,这意味着您的关联可能是正确的。


    来源:https://www.codenong.com/26471993/

    微信公众号
    手机浏览(小程序)

    Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

    Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

    Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9393.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
    0
    分享到:
    没有账号? 忘记密码?