Kohana ORM Relationships and Displaying Information - orm

I don't know how to approach this.
Lets say I have 3 models, A, B, and C.
Model A has many C, Model B has many C, C belongs to A and B.
I get all of B.
$getBs=ORM::factory('B')->find_all();
I display A, B, C.
foreach($getBs as $getB)
{
echo $getB->b_category_title;
foreach($getB->C->find_all() as $getC)
{
echo $getC->c_title;
echo $getA->a_author; //Problem part
}
}
I do not know how to access and connect Model A to Model C when displaying information for Model C.
Edit
To get working code, I change Model A - C to Model One - Three.
Using biakaveron example of _load_with, I get the following error:
Database_Exception [ 1054 ]: Unknown column 'three.id_c' in 'on clause' [ SELECT `ones`.`a_id` AS `ones:a_id`, `ones`.`a_author` AS `ones:a_author`, `three`.* FROM `threes` AS `three` JOIN `twos_threes` ON (`twos_threes`.`id_c` = `three`.`c_id`) LEFT JOIN `ones` AS `ones` ON (`ones`.`a_id` = `three`.`id_c`) WHERE `twos_threes`.`id_b` = '1' ]
Models:
class Model_One extends ORM {
protected $_primary_key = 'a_id';
protected $_has_many = array(
'threes'=> array(
'model' => 'three',
'through' => 'ones_threes',
'far_key' => 'id_c',
'foreign_key' => 'id_a'
),
);
}
class Model_Two extends ORM {
protected $_primary_key = 'b_id';
protected $_has_many = array(
'threes'=> array(
'model' => 'three',
'through' => 'twos_threes',
'far_key' => 'id_c',
'foreign_key' => 'id_b'
),
);
}
class Model_Three extends ORM {
protected $_primary_key = 'c_id';
protected $_belongs_to = array(
'ones'=> array(
'model' => 'one',
'through' => 'ones_threes',
'far_key' => 'id_a',
'foreign_key' => 'id_c'
),
'twos'=> array(
'model' => 'two',
'through' => 'twos_threes',
'far_key' => 'id_b',
'foreign_key' => 'id_c'
),
);
protected $_load_with = array('ones');
}
Why is it looking for three.id_c?

C belongs to A and B.
foreach($getBs as $getB)
{
echo $getB->b_category_title;
foreach($getB->C->find_all() as $getC)
{
echo $getC->c_title;
echo $getC->A->a_author;
}
}
PS. Just a note. You can load both C and A objects using $_load_with property:
class Model_C extends ORM {
// ...
protected $_load_with = array('A');
// ...
}

Related

How to access relationship data in groupgridview with extraRowColumns

The Database Tables:
project_master (id, project_name)
task_master (id, task_name, project_id)
Relationship in the TaskMaster Model:
TaskMaster.php
class TaskMaster extends CActiveRecord
{
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'ProjectsRpl' => array(self::BELONGS_TO, 'Projects', 'project_id'),
);
}
}
Following GroupGridView view file:
Task.php
$this->widget('ext.groupgridview.GroupGridView', array(
'id' => 'Customer-grid',
'dataProvider' => $modelCustomer->searchCustomer(),
//'mergeColumns' => 'project_id',
'extraRowColumns' => array('ProjectsRpl.project_name'),
'extraRowPos' => 'above',
'afterAjaxUpdate' => 'function(){}',
'columns'=>$columns,
));
GroupGridView reference site.
Getting the following errors:
CException: Column or attribute "ProjectsRpl.project_name" not found!
Only one change in Task.php file.
$this->widget('ext.groupgridview.GroupGridView', array(
'id' => 'Customer-grid',
'dataProvider' => $model->search(),
//'mergeColumns' => 'project_id',
'extraRowColumns' => array('project_id'),
'extraRowPos' => 'above',
'extraRowExpression' => '"<b style=\"color: black\">".$data->ProjectsRpl->project_name."</b>"',
'afterAjaxUpdate' => 'function(){}',
'ajaxUrl' => Yii::app()->createUrl('customer/index'),
'ajaxUpdate' => true,
'enablePagination' => true,
"summaryText" => true,
'enableSorting' => FALSE,
'columns'=>$columns,
));

How to use Yii trait in controller

In my controllers a lot of code, about 1000 lines
Advise how you can make more convenient, for example to make a piece of code in trait
components/ProductTrait.php
trait ProductTrait{
protected function getProductProvider(Product $model){
$dataProductProvider = new CActiveDataProvider('Product', array(
'criteria' => array(
'limit' => $pageLimit,
'condition' => 't.creatorId = :creatorId AND t.categoryId =:categoryId',
'order' => 't.created DESC',
'params' => array(
':creatorId' => $model->creatorId,
':categoryId' => $model->categoryId,
),
),
'pagination' => false,
'sort' => false,
));
return $dataProductProvider;
}
}
Controller
class DealerController extends Controller{
use ProductTrait;
public function actionView($id){
$model = $this->loadModel($id);
if ($model === null) {
throw new CHttpException(404, 'The requested page does not exist.');
}
$renderParams['productProvider'] = $this->getProductProvider($model);
}
}
You can use Trait, but you can also use behaviors.
First you declare your behavior
class ProductBehavior extends CBehavior
{
protected function getProductProvider(Product $model){
$dataProductProvider = new CActiveDataProvider('Product', array(
'criteria' => array(
'limit' => $pageLimit,
'condition' => 't.creatorId = :creatorId AND t.categoryId =:categoryId',
'order' => 't.created DESC',
'params' => array(
':creatorId' => $model->creatorId,
':categoryId' => $model->categoryId,
),
),
'pagination' => false,
'sort' => false,
));
return $dataProductProvider;
}
}
Then you use it in your controller (don't forget to attach it, I've done it in the init method)
class DealerController extends Controller{
public function init() {
//Attach the behavior to the controller
$this->attachBehavior("productprovider",new ProductBehavior);
}
public function actionView($id){
$model = $this->loadModel($id);
if ($model === null) {
throw new CHttpException(404, 'The requested page does not exist.');
}
//We use the behavior methods as if it is one of the controller methods
$renderParams['productProvider'] = $this->getProductProvider($model);
}
}
The main point of behaviors is it's working in php 5.3 whereas trait are not.
Now here's some difference between traits and behaviors:
A first difference with behaviors is that traits can not be parameterized.
In your controller you could declare the behaviors this way:
public function behaviors(){
return array(
'ProductBehavior ' => array(
'class' => 'components.behaviors.ProductBehavior',
'firstAttribute' => 'value',
'secondAttribute' => 'value',
)
);
}
Your ProductBehavior class would have 2 public attributes: firstAttribute and secondAttribute.
One thing traits lack when compared to behaviors is runtime attachement. If you want to extend a given (let's say 3rdParty) class with some special functionality, behaviors give you a chance to attach them to the class (or more specifically to instances of the class). Using traits, you had to to modify the source of the class.
A Wiki about behaviors
The Yii Guide
The CBehavior doc

How to use the InputFilter in a nested mapper model class in Zend Framework 2?

Everyone, who started ZF2 learning with the "Get started" tutorial, will know the model class Album (s. below).
Now I want to extend my model with songs. One album can have 0 or more songs. The songs will get a new talbe songs (id, title, album_id) and the mapper Album\Model\Song. The mapper Album\Model\Song will be built similar to Album\Model\Album. The mapper Album\Model\Album will get a new property songCollection (array of Album\Model\Song objects or maybe something like Album\Model\SongCollection object).
Does it make sence to use the InputFilter for "nested" (mapper) classes?
How should the getInputFilter() be modified?
How should the setInputFilter() be modified? OK, now it is not implemented at all. But it's approximately clear how to do it for a shallow class structure -- and not clear how to implement it for a mapper, that references another mapper(-s).
Album\Model\Album
<?php
namespace Album\Model;
use Zend\Stdlib\ArraySerializableInterface;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class Album implements InputFilterAwareInterface, ArraySerializableInterface {
public $id;
public $artist;
public $title;
protected $inputFilter;
public function exchangeArray(array $data) {
$this->id = (isset($data['id'])) ? $data['id'] : null;
$this->artist = (isset($data['artist'])) ? $data['artist'] : null;
$this->title = (isset($data['title'])) ? $data['title'] : null;
}
public function toArray() {
return $this->getArrayCopy();
}
public function getArrayCopy() {
return get_object_vars($this);
}
public function setInputFilter(InputFilterInterface $inputFilter) {
throw new \Exception('Not used');
}
public function getInputFilter() {
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int')
)
)));
$inputFilter->add($factory->createInput(array(
'name' => 'artist',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim')
),
'validarots' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100
)
)
)
)));
$inputFilter->add($factory->createInput(array(
'name' => 'title',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim')
),
'validarots' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100
)
)
)
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
I think you are a little confused with the relationship with the models and mappers set out in this example.
The 'mappers' would be the TableGateway objects, such as AlbumTable, SongTable etc. The Album and Song classes yo would call models, or Domain Objects, these are what represent the actual entities in your application. The Mappers just take care of persisting them in your database etc.
When using the TableGateway implementation, I would let each Domain Object (such as Ablum) handle the InputFilter for the attributes it's TableGateway is going to persist (such as AlbumTable).
For the example you stated, I would not change the Album Models InputFilter at all. The reason is the relationship with Songs is this:
Album HAS many songs, Song Belongs to Album (the Song would have the link back to the Album)
Add a new Song Object and Gateway:
<?php
namespace Album\Model;
use Zend\Stdlib\ArraySerializableInterface;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class Song implements InputFilterAwareInterface, ArraySerializableInterface {
protected $id;
protected $album;
protected $title;
protected $inputFilter;
// Added Getters / Setters for the attributes rather than
// having public scope ...
public function setAlbum(Album $album)
{
$this->album = $album;
}
public function getAlbum()
{
return $this->album;
}
public function exchangeArray(array $data) {
$this->id = (isset($data['id'])) ? $data['id'] : null;
$this->title = (isset($data['title'])) ? $data['title'] : null;
if(isset($data['album_id'])) {
$album = new Album();
$album->exchangeArray($data['album_id']);
$this->setAlbum($album);
}
}
public function toArray() {
return $this->getArrayCopy();
}
public function getArrayCopy() {
return array(
'id' => $this->id,
'album_id' => $this->getAlbum()->id,
'title' => $this->title,
);
}
public function setInputFilter(InputFilterInterface $inputFilter) {
throw new \Exception('Not used');
}
public function getInputFilter() {
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int')
)
)));
$inputFilter->add($factory->createInput(array(
'name' => 'album_id',
'required' => true,
'filters' => array(
array('name' => 'Int')
)
)));
$inputFilter->add($factory->createInput(array(
'name' => 'title',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim')
),
'validarots' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100
)
)
)
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
Notice no need to change the Album Model as the relationship is 'Song Belongs to Album'.
When you object relationships get more complex you will want to look at using Hydrators to build the objects for you (http://framework.zend.com/manual/2.0/en/modules/zend.stdlib.hydrator.html)
Now you would create a SongTable to persist this new Object for you:
<?php
namespace Album\Model;
use Zend\Db\TableGateway\TableGateway;
class SongTable
{
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function getSong($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
public function saveSong(Song $song)
{
$data = array(
'album_id' => $song->getAlbum()->id,
'title' => $song->title,
);
$id = (int)$song->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getSong($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Form id does not exist');
}
}
}
public function fetchAlbumSongs(Album $album)
{
$resultSet = $this->tableGateway->select(array(
'album_id' => $album->id
));
return $resultSet;
}
public function addSongsToAlbum(Album $album)
{
foreach($this->fetchAlbumSongs($album) as $song) {
$album->addSong($song);
}
}
}
You Could then Modify you Album model to allow Songs to be added:
class Album implements InputFilterAwareInterface, ArraySerializableInterface {
// Other stuff here
/**
* #var array
*/
protected $songs = array();
public function addSong(Song $song)
{
$this->songs[] = $song;
}
public function getSongs()
{
return $this->songs;
}
}
You can then build your object graph easily, I would usually make a server to do do this kind of thing:
AlbumService.php
public function getAlumbWithSongs(int $id)
{
$album = $this->getAlbumTable()->getAlbum($id);
if($album) {
$this->getSongTable()->addSongsToAlbum($album);
}
return $album;
}

Kohana ORM Display Information

I'm trying to learn how to display information from two tables.
Tables:
categories {category_id, category_title}
forums {forum_id, forum_title}
categories_forums {id_category, id_forum}
Models:
class Model_Forum extends ORM {
protected $_primary_key = 'forum_id';
protected $_belongs_to = array(
'categories'=> array(
'model' => 'category',
'through' => 'categories_forums',
'far_key' => 'id_category',
'foreign_key' => 'id_forum'
),
);
}
class Model_Category extends ORM {
protected $_primary_key = 'category_id';
protected $_has_many = array(
'forums'=> array(
'model' => 'forum',
'through' => 'categories_forums',
'far_key' => 'id_forum',
'foreign_key' => 'id_category'
),
);
}
I'm unsure how to display.
So far I have the following:
$categories = ORM::factory('category');
$forums = $categories->forums->find_all();
I don't how to display category_id, category_title, forum_id, forum_title.
You can use foreach loops, like this:
$categories = ORM::factory('category');
foreach ($categories->find_all() as $category){
echo $category->category_title, ' ', $category->id;
}
The following seems to work:
$categories = ORM::factory('category')->find_all();
$view = new View('default/index');
$view->categories = $categories;
$this->response->body($view);
foreach ($categories as $category) :
echo $category->category_title;
echo $category->category_id;
foreach ($category->forums->find_all() as $forum) :
echo $forum->forum_title;
echo $forum->forum_id;
endforeach;
endforeach;

Kohana 3.2 ORM many-to-many - wrong field names

I trying to make many-to-many relation between 2 models: Users_Role and Users_Right
class Model_Users_Role extends ORM{
protected $_has_many = array(
'rights' => array(
'model' => 'users_right',
'through' => 'users_roles_rights',
),
);
}
class Model_Users_Right extends ORM{
protected $_has_many = array(
'roles' => array(
'model' => 'users_role',
'through' => 'users_roles_rights',
),
);
}
I'm trying to do this:
$role = ORM::factory('users_role', 1);
$right = ORM::factory('users_right', 1);
$right->add('roles', $role);
Error:
Database_Exception [ 1054 ]: Unknown column 'role_id' in 'field list' [ INSERT INTO `users_roles_rights` (`users_right_id`, `role_id`) VALUES ('1', '1') ]
I tryed to make it on the other side:
$role = ORM::factory('users_role', 1);
$right = ORM::factory('users_right', 1);
$role->add('rights', $right);
New error:
Database_Exception [ 1054 ]: Unknown column 'right_id' in 'field list' [ INSERT INTO `users_roles_rights` (`users_role_id`, `right_id`) VALUES ('1', '1') ]
I expected ORM to use users_role_id and users_right_id field names in pivot table, but it uses wrong name of far key? Where I have made a mistake?
Check out where the default values are set.
Try this:
class Model_Users_Role extends ORM{
protected $_has_many = array(
'rights' => array(
'model' => 'users_right',
'far_key' => 'users_right_id',
'through' => 'users_roles_rights',
),
);
}
class Model_Users_Right extends ORM{
protected $_has_many = array(
'roles' => array(
'model' => 'users_role',
'far_key' => 'users_role_id',
'through' => 'users_roles_rights',
),
);
}
Kohana does not check that the relationship does not already exist.
Either enforce this in the database table with a composite unique key on the two foreign key columns, or make your code check that the relationship does not already exist before adding.