我是PHP和MySQL的新手。我正在Cphalcon框架上构建自己的动漫CMS,但与多对多的关系存在一些问题,并且无法正确查询。
我在MariaDB上有3个表:
动漫:
id
title
slug
cover
季节:
id
name
animeId
情节:
id
animeId
seasonsId
name
cover
还有phalcon的3种型号:
动漫:
<?php
namespace LearnPhalcon\Models;
use Phalcon\Mvc\Model;
use Phalcon\Validation;
use Phalcon\Validation\Validator\Uniqueness;
class Anime extends Model
{
public $id;
public $title;
public function initialize()
{
$this->hasMany('id', __NAMESPACE__ . '\Seasons', 'animeId', [
'alias' => 'seasons'
]);
$this->hasMany('id', __NAMESPACE__ . '\Episodes', 'animeId', [
'alias' => 'episodes'
]);
}
}
季节:
<?php
namespace LearnPhalcon\Models;
use Phalcon\Mvc\Model;
use Phalcon\Validation;
use Phalcon\Validation\Validator\Uniqueness;
class Seasons extends Model
{
public $id;
public $name;
public function initialize()
{
$this->belongsTo('id', __NAMESPACE__ . '\Anime', 'id', [
'alias' => 'anime'
]);
$this->hasMany('id', __NAMESPACE__ . '\Episodes', 'seasonsId', [
'alias' => 'episodes'
]);
}
}
情节:
<?php
namespace LearnPhalcon\Models;
use Phalcon\Mvc\Model;
use Phalcon\Validation;
use Phalcon\Validation\Validator\Uniqueness;
class Episodes extends Model
{
public $id;
public $name;
public function initialize()
{
$this->belongsTo('id', __NAMESPACE__ . '\Anime', 'id', [
'alias' => 'anime'
]);
$this->belongsTo('id', __NAMESPACE__ . '\Seasons', 'id', [
'alias' => 'seasons'
]);
}
}
索引控制器内部的操作:
public function aniAction($slug)
{
$slug = $this->dispatcher->getParam('slug');
$ani = Anime::findFirst(array(
'slug = :slug:',
'bind' => array(
'slug' => $slug
)));
if ($ani === false) {
$this->dispatcher->forward(array(
'controller' => 'Error',
'action' => 'ops'
));
}
$this->view->setVar('ani', $ani);
$this->view->setTemplateBefore('public');
}
视图:
{% for seasons in ani.seasons %}
{{ seasons.name }}
<br/>
{% for episodes in seasons.episodes %}
{{ episodes.name }}
<br/>
{% endfor %}
{% endfor %}
实际上该代码有效,但是 它只返回第一季的情节,而不是每个季节的情节
数据库示例:
动漫:
ID: 1
Title: Test Anime
Slug: test-anime
Cover: /var/uploads/test.png
季节:
--------------------
ID: 1
Name: Season 1
animeId: 1
--------------------
ID: 2
Name: Season 2
animeId: 1
--------------------
情节:
--------------------
ID: 1
animeId: 1
seasonsId: 1
name: Test Name
cover: n/d
---------------------
ID: 2
animeId: 1
seasonsId: 1
name: Test Name2
cover: n/d
---------------------
ID: 3
animeId: 1
seasonsId: 2
name: Test Name3
cover: n/d
---------------------
从实际的测试操作中,我得到了HTML:
Season 1
Test Name
Test Name2
Season 2
(and here nothing)
should be Test Name3?
答案 0 :(得分:0)
如果您要问如何建立多对多关系
动漫:
$this->hasManyToMany('id',__NAMESPACE__ . '\Episodes','animeId','seasonsId',__NAMESPACE__ . '\Seasons','id',['alias'=>'Seasons']);
季节:
$this->hasManyToMany('id',__NAMESPACE__ . '\Episodes','seasonsId','animeId',__NAMESPACE__ . '\Anime','id',['alias'=>'Anime']);