【问题标题】:Multiple belongsTo() associations in CakePHP 3.xCakePHP 3.x 中的多个 belongsTo() 关联
【发布时间】:2015-05-07 21:14:38
【问题描述】:

我正在使用 CakePHP 3.x。
我的问题是:是否有可能有许多属于同一个外键的关联()?

这是我的问题:
我的表中有三个字段使用相同的外键。

在模型表中,我以这种方式使用了 belongsTo() 关联:

$this->belongsTo('Pilotes', [
    'className' => 'Users',
    'foreignKey' => 'pilote',
    'propertyName' => 'pilote_user'
]);

$this->belongsTo('Verificateurs', [
    'className' => 'Users',
    'foreignKey' => 'no_user',
    'propertyName' => 'verificateur_user'
]);

$this->belongsTo('Users', [
    'className' => 'Users',
    'foreignKey' => 'no_user',
    'propertyName' => 'user'
]);

但是当我调试我的实体时,前两个字段只包含外键,最后一个就可以了。

查询:

public function view($id = null)
{
    $demande = $this->Demandes->get($id, [
        'contain' => ['Users']
    ]);
    $this->set('demande', $demande);
    $this->set('_serialize', ['demande']);
}

这是 debug() 的输出:

object(App\Model\Entity\Demande) {
'new' => false,
'accessible' => [
    'pilote' => true,
    'verificateur' => true,
    'pilote_user' => true,
    'verificateur_user' => true,
    'user' => true,
],
'properties' => [
    'no_demande' => (int) 4,
    'pilote' => (int) 3,
    'verificateur' => (int) 2,
    'no_user' => (int) 1,
    'user' => object(App\Model\Entity\User) {
        /* Details of the user */
    },
],
'dirty' => [],
'original' => [],
'virtual' => [],
'errors' => [],
'repository' => 'Demandes'
}

如果我评论我的最后一个 belongsTo(),第二个字段很好,但不是第一个。

提前致谢

【问题讨论】:

  • 什么查询会产生这个结果?
  • 我在帖子中添加了查询
  • 你需要包含其他关联'contain' => ['Users', 'Verificateurs', 'Pilotes']

标签: cakephp cakephp-3.0


【解决方案1】:

更改第一个参数中的名称:

$this->belongsTo('Pilotes', [
    'className' => 'Users',
    'foreignKey' => 'pilote',
    'propertyName' => 'pilote_user'
]);

$this->belongsTo('Verificateurs', [
    'className' => 'Users',
    'foreignKey' => 'verificateur',
    'propertyName' => 'verificateur_user'
]);

$this->belongsTo('Users', [
    'className' => 'Users',
    'foreignKey' => 'no_user',
    'propertyName' => 'user'
]);

请注意,当您选择使用 piloteverificateur 作为架构中的列名时,您需要更改 propertyName 的值。这是因为 Cake 将在您的实体中使用该名称创建一个属性,并且它将与您的表中的属性发生冲突。

这就是我必须选择pilote_user 作为您实体的属性名称的原因。

查询您的数据时,您需要将'contain' => ['Users', 'Verificateurs', 'Pilotes'] 添加到查找器选项中

【讨论】:

  • 我仍然只使用您的代码获取外键。外键是我的三个关联的同一个字段,只是值在变化
  • 三个belongsTo关联不能是同一个外键,原因我希望很明显:)
  • 也许我误解了食谱中的某些内容,但为什么我不能为不同的属性使用相同的外键? belongsTo() 代表一个关联 1-n,不是吗?
  • 那不是hasMany吗?表中的 1 条记录在另一个中有 n 条,对我来说就是 hasMany。一个 belongsTo 关联是 n - 1
  • 我托管了一张我的桌子截图hereno_userpiloteverificateurno_user的外键,应该是belongsTo()吧?另一方面,我的表Users 中有hasMany()。我完全错了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-14
  • 1970-01-01
  • 2017-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多