【问题标题】:CakePHP 3 table relationsCakePHP 3 表关系
【发布时间】:2017-03-03 10:11:04
【问题描述】:

我有以下表格:cars、car_types 和 car_methods。我的问题是关系。汽车有一种类型和一种方法。

我的目标是展示汽车和他的附件“汽车类型”和“汽车方法”。

汽车表:

id - type_id - method_id

Car_types 表:

id - type

Car_methods 表:

id - method

如何在我的模型表中进行设置,以便我可以在我的控制器中执行以下操作:

$this->Cars->CarTypes->find('all');

我尝试如下,但它会给出一个没有关联的错误:

车型:

class CarsTable extends Table {
public function initialize(array $config)
{
    parent::initialize($config);

    $this->setTable('cars');
    $this->setDisplayField('id');
    $this->setPrimaryKey('id');

    $this->hasOne('CarTypes', [
        'className' => 'Cars.CarTypes',
        'foreignKey' => 'type_id',
        'propertyName' => 'type'
    ]);

    $this->hasOne('CarMethods', [
        'className' => 'Cars.CarMethods',
        'foreignKey' => 'method_id',
        'propertyName' => 'method'
    ]);
}
}

车型:

class CarTypesTable extends Table {

public function initialize(array $config) {
    parent::initialize($config);

    $this->setTable('car_types');
    $this->setDisplayField('id');
    $this->setPrimaryKey('id');

    $this->hasMany('Cars', [
        'foreignKey' => 'type_id'
    ]);
}
}

CarMethots 模型:

class CarMethodsTable extends Table {

public function initialize(array $config) {
    parent::initialize($config);

    $this->setTable('car_method');
    $this->setDisplayField('id');
    $this->setPrimaryKey('id');

    $this->hasMany('Cars', [
        'foreignKey' => 'method_id'
    ]);
}
}

【问题讨论】:

  • 是的,我已经尝试过文档,但我不太明白。我已经为你添加了代码。
  • 它有很多类型和方法的汽车。像现在一样,指向表本身的类型和方法。做本书中的教程或一些关于如何关联日期的通用 SQL 教程。 :)

标签: mysql cakephp cakephp-3.0


【解决方案1】:

你的最后两个关系是错误的,这是好的

车型:

public function initialize(array $config) {
    $this->hasMany('Cars', [  //A CarType hasMany Cars
        'foreignKey' => 'type_id'
    ]);
}

CarMethods 模型:

public function initialize(array $config) {
    $this->hasMany('Cars', [  //A CarMethod hasMany Cars
        'foreignKey' => 'method_id'
    ]);
}

控制器动作

对于您的查询,将这两个关系添加到包含选项:

//Get all cars with type and method
$this->Cars->find('all',
     [
        'contain' => ['CarTypes', 'CarMethods'] 
     ]
);

【讨论】:

  • 我已经用你的例子更新了我的问题中的模型,但我仍然得到一个(无法导出对象:Cars is not associated with CarTypes and CarMethods)}。
  • 我已经解决了。我的模型的名称空间未链接到我的插件。有时一个问题就是这么简单。 :) 感谢您的帮助!
【解决方案2】:

belongsTo 关联是对 hasOne 和 hasMany 关联的自然补充:它允许我们从另一个方向查看数据。

belongsTo:当前模型包含外键。

如果您的表中有外键,则该表将属于关联表。所以,在你的情况下:

public function initialize(array $config) {
     $this->belongsTo('CarTypes', [
        'foreignKey' => 'type_id',
        'joinType' => 'LEFT'
     ]);

     $this->belongsTo('CarMethods', [
         'foreignKey' => 'method_id',
         'joinType' => 'LEFT'
     ]);
}

之后你可以使用$this->Cars->CarTypes->find('all');

【讨论】:

    猜你喜欢
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多