CakePHP 3.0 cannot get 2 items from 1 table

主宰稳场 提交于 2019-12-20 05:36:04

问题


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

Code in Controller:

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

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

Please tell me how to do it

Thanks very much!


回答1:


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'
]);

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));

And then in the template use

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


来源:https://stackoverflow.com/questions/30412066/cakephp-3-0-cannot-get-2-items-from-1-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!