Phalcon php orm can't relate tables -
i'm trying setup 3 tables relationship in phalcon, doesn't seem work. plese tell me doing wrong? here erd of these tables: (erd diagram) here code models , controller
authors.php (model) <?php class authors extends \phalcon\mvc\model { /** * * @var integer */ public $id; /** * * @var string */ public $name; /** * * @var string */ public $lastname; /** * initialize method model. */ public function initialize() { $this->setsource('authors'); $this->hasmany('id', 'authorbook', 'authorid'); } /** * independent column mapping. */ public function columnmap() { return array( 'id' => 'id', 'name' => 'name', 'lastname' => 'lastname' ); }
books.php(model)
<?php class books extends \phalcon\mvc\model { /** * * @var integer */ public $id; /** * * @var string */ public $name; /** * * @var string */ public $yearpublished; /** * * @var string */ public $picture; /** * initialize method model. */ public function initialize() { $this->setsource('books'); $this->hasmany('id', 'authorbook', 'bookid'); } /** * independent column mapping. */ public function columnmap() { return array( 'id' => 'id', 'name' => 'name', 'yearpublished' => 'yearpublished', 'picture' => 'picture' ); } } }
authorbook.php (model):
<?php class authorbook extends \phalcon\mvc\model { /** * * @var integer */ public $id; /** * * @var integer */ public $authorid; /** * * @var integer */ public $bookid; /** * initialize method model. */ public function initialize() { $this->setsource('authorbook'); $this->belongsto('authorid', 'authors', 'id'); $this->belongsto('bookid', 'books', 'id'); } /** * independent column mapping. */ public function columnmap() { return array( 'id' => 'id', 'authorid' => 'authorid', 'bookid' => 'bookid' ); } }
admincontroller.php
public function indexaction() { $this->view->disablelevel(view::level_main_layout); $this->view->setvar('books', books::find()->toarray()); } }
so question how can access author of book? because when print out books array in view thing :
array ( [0] => array ( [id] => 1 [name] => javascript: parts [yearpublished] => 2014-04-18 [picture] => javascript-the-good-parts.jpg ) ...
you should use hasmanytomany n-n relationship authors , books models, (if i'm not wrong, author has many books , books has many authors)
so models should this: authors:
public function initialize(){ $this->setsource('authors'); $this->hasmanytomany('id', 'authorbook', 'authorid', 'bookid', 'books', 'id', array( 'alias' => 'books' )); }
same books model, have use hasmanytomany function:
public function initialize(){ $this->setsource('books'); $this->hasmanytomany('id', 'authorbook', 'bookid', 'authorid', 'author', 'id', array( 'alias' => 'authors' )); }
the authorbook model relations correct.
now can author(s) of book simple call alias have defined in relations:
$book = books::findfirst(); $bookauthor = $book->authors->toarray()
that's it.
Comments
Post a Comment