本文介绍了CakePHP 3.0无法从1个表中获得2个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一场足球比赛中,我有2个俱乐部 Home-Club和 Away-Club。我已经在MySQL中创建了表 match和 club。在匹配表中有2个外键 home_id和 away_id。我正在使用cakePHP显示列表匹配项,匹配信息包含 Home-Club和 Away-Club的名称。如何在模板文件(.ctp文件)中获取 Home-Club和 Away-Club的名称。
现在我在模板文件中使用以下代码:

In a football match i have 2 clubs "Home-Club" and "Away-Club" . I have created table "match" and "club" in MySQL. In "match" table has 2 foreign key "home_id" and "away_id". I'm using cakePHP to show list matches, match information contain names of "Home-Club" and "Away-Club". How to get name of "Home-Club" and "Away-Club" in template file ( .ctp file ). For now I using this code in the template file:

$match->club->name

控制器中的代码:

public function index()
    {
        $this->paginate = [
            'contain' => ['Club']
        ];
        $this->set('match', $this->paginate($this->Match));
        $this->set('_serialize', ['match']);
    }

它始终显示 Away-Club的名称。我不知道如何命名 Home-Club

It always show name of "Away-Club". I don't known how to get name of "Home-Club"

请告诉我怎么做

非常感谢!

推荐答案


问题在于 belongsTo 关联。尝试以这种方式重新定义它:

Problem is in definition of belongsTo associations. Try to redefine it this way:

$this->belongsTo('HomeClub', [
    'className' => 'Club',
    'foreignKey' => 'home_id',
    'propertyName' => 'home_club'
]);
$this->belongsTo('AwayClub', [
    'className' => 'Club',
    'foreignKey' => 'away_id',
    'propertyName' => 'away_club'
]);

belongsTo 关联的名称必须唯一。现在将它们包含在控制器中

Names of belongsTo associations have to be unique. Now contain them in the controller

// ...
$this->paginate = [
    'contain' => ['HomeClub', 'AwayClub']
];
$this->set('matches', $this->paginate($this->Match));

然后在模板中使用

<?= $match->home_club->name ?>
<?= $match->away_club->name ?>

这篇关于CakePHP 3.0无法从1个表中获得2个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 13:22