Yii Framework, how to fetch related table data? - php

I am new to yii and the model relation is new to me. I am currently doing a system that has a table structure:
products
PK id
brand
product_locales
PK id
FK product_id
name
locale
product_relations
PK id
FK product_id
FK related_id
my Product model relation:
public function relations()
{
return array(
'productlocales' => array(self::HAS_MANY, 'ProductLocale', 'product_id'),
'relations' => array(self::MANY_MANY, 'Product', 'product_relations(product_id, related_id)')
);
}
then my Product Locale Relation:
public function relations()
{
return array(
'product' => array(self::BELONGS_TO, 'Product', 'product_id')
);
}
in my Product Controller when I call this code:
$product = ProductLocale::model()->findByPk(1);
var_dump($product->product->relations);
it outputs the id and brand of a related product from the product table. but what I want to output is all the locales of the product, which is the name and the locale.
Can anyone help me out with this?
Thanks in advance.

I don't understand the product_relations table, and seems like the relation whith Product is HAS_MANY, not MANY_MANNY.
In any case, if I have understood, you need find the id of product and then find all the product_locale with this id:
$prodLoc=ProductLocale::model()->findByPk(1);
$arrayProdLoc=ProductLocale::model()->findAllByAttributes('product_id'=>$prodLoc->product_id);
ArrayProd will have models for all product_locale related with the same product.
If you want show this information in a gridview, you probabli will want a DataProvider:
$prodLoc=ProductLocale::model()->findByPk(1);
$provider=CActiveDataprovider('ProductLocale',array (
'criteria'=>array(
'condition'=>'product_id='.$prodLoc->product_id,
));
You can also define a new self-relation into product_locale Model:
public function relations()
{
return array(
'product' => array(self::BELONGS_TO, 'Product', 'product_id'),
'productsLocRelated'=>array(self::HAS_MANY,'ProductLocale',array('product_id'=>'product_id')),
);
}
So you can have all products_locale by:
$prodLoc=ProductLocale::model()->findByPk(1);
$arrayProdLoc=$prodLoc->productsLocRelated;
Note: I haven't tested the code.

Related

Creating a subcategory for Category in yii

I have certain products..now i want to create a subcategory for those product..i created a table for subcategory with category as foreign key...
Please anybody help me to achieve this
I think the best way to do it is to go to YOURDOMAIN/index.php/gii
And you create your models and the relations using the interface.
Thanks
You can create a model SubCategory like you did for Category, but with this relation:
public function relations()
{
return array(
'category' => array(self::BELONGS_TO, 'Category', 'category_id'),
);
}
In Category you can add this relation:
public function relations()
{
return array(
'subCategories' => array(self::HAS_MANY, 'SubCategory', 'category_id'),
);
}

Yii CGridView, I can't display fields form other model using HAS_MANY relationship

I have a HAS_MANY relation between 2 models, i use bookID as foreign key
model 1 - Importedbooks, Importedbooks can have many CountryOfImport
public function relations()
{
return array(
'CountryOfImportObj'=>array(self::HAS_MANY, 'CountryOfImport', 'bookID')
);
}
model 2 CountryOfImport, CountryOfImport belongs to Importedbooks
public function relations()
{
return array(
'ImportBooksObj'=>array(self::BELONGS_TO, 'Importedbooks', 'bookID')
);
}
Now, For my CGridView i am using a model->search()of the Importedbooks model as my dataProvider, From here is where i get stuck.
CGridView
$data = $model->search();
$data->setPagination(array('pageSize'=>'5'));
$data->criteria->addCondition('active = "yes"');
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$data
,'filter'=>$model
,'pager'=>array('header'=>'')
,'columns'=>array(
'id',
'bookYear',
'bookTitle',
'DISPLAY VALUE FROM OTHER model HERE'
)
)
);
DataProvider of the Imported books model, i'm using this as my data provider for the grid
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('bookID',$this->bookID);
$criteria->compare('countryName',$this->countryName,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
The relation works because i can use below code in my controller to get a field(countryName) from the other model
$model = Importedbooks::model()->with('CountryOfImportObj')->findbyPK(3);
print_r($model->CountryOfImportObj[0]->countryName);
Such as Importedbooks have many CountryOfImport, in one row you must show or all country names or concreet names depending on ID or countryName or some other attribute.
You can pass anonymous function as value:
'columns' => array(
'id',
'bookYear',
'bookTitle',
array(
'header' => 'Countries',
'type' => 'raw',
// if you have defined counrtyName attribute in 'Importedbooks' model, if not you can remove this row
// also CGridView 'uses' attribute 'name' for filtering or sorting
'name' => 'countryName',
'value' => function($data, $row) { //$data is item of DataProvider, $row is number of row (starts from 0)
$countries = CHtml::listData((array)$data->CountryOfImportObj, 'id', 'countryName');
return implode(', ', $countries);
}
)
)
If you want to filter or sort by external attributes too, you must "declare them"
Thanks!

Yii multiple relations between different models in different modules

How would i add a 3rd relation to my relations() function to join the CommentsPosts model with the store model. Where CommentsPosts.store_id = Store.id and CommentsPosts.store_zip = Store.zip?
in my comment.php
public function relations()
{
return array(
'user' => array(self::BELONGS_TO, $this->module->userModelClass, 'userId'),
'posts' => array(self::HAS_MANY, "CommentsPosts", array("commentId" => "id")),
'store'=>'',
);
}
CommentsPost.php is in modules/comments/model and Store.php is in modules/store/model
FYI, i'm using Yii 1.1.15
I'm not sure about your relations but try something like bellow
In Comment post Model add the relation
public function relations()
{
return array(
'store' => array(self::HAS_MANY, "Store", array("store_id" => "id")),
);
}
When retrieving
$enity->post // give all post
$enity->post[i]->store // gives the each post data of store

Retrieving data using relationships in Yii PHP

Hi I have a database where i use a link table to link products and categories.
The relationships look like this:
Product ProductCategories Category
Id Id Id
Name ProductId Name
CategoryId
So the productCategory table links Products to Categories
My problem is when im trying to find all Products under the category with the Id of 1
I use this code but it doesnt seem to be working:
$models = Products::model()->with('productcategories')->findByPk(1);
This is the Products Relationships:
public function relations()
{
return array(
'productcategories' => array(self::HAS_MANY, 'Productcategories', 'ProductId'),
);
}
public function relations()
{
return array(
'productcategories' => array(self::HAS_MANY, 'Productcategories', 'ProductId'),
'Categories' => array(self::HAS_MANY, 'Category', '',
'through'=>'productcategories',
'on' => 'Categories.Id = productcategories.CategoryId',
),
);
}
// Get all Product with a Category with id = 1
$models = Products::model()->with('Categories')->findAll('Categories.Id = 1');

Yii - Self Referencing Table

This is my category table
id category parent_category_id
1 animal NULL
2 vegetable NULL
3 mineral NULL
4 doggie 1
5 potato 2
6 hunting 4
my yii grid view shows parent category id instead of name.
how can i display the parent category name in grid view.
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'category-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'category',
'parent_category_id',
array(
'class'=>'CButtonColumn',
),
),
)); ?>
what changes i have to make in the above code.
thanks.
First step - define relation in model class:
public function relations()
{
return array(
'parent'=>array(self::BELONGS_TO, 'Category', 'parent_category_id'),
);
}
where Category - is name of AR model class, parent_category_id - foreign key referencing to itself.
Step 2 - CGridView, columns attribute:
...
'columns'=>array(
'id',
'category',
array(
'name'=>'Parent category', // col title
'value'=>function (Category $data){
if($data->parent_category_id)
return $data->parent->category; // "parent" - relation name, defined in "relations" method
return "-= root category =-";
}
),
)
...
Note: code above requires php version>=5.3. Otherwise you have to avoid using anonymous function
'columns'=>array(
.....
array('name'=>'id','value'=>'$data->Category->name'),
)
or create function inside call getCategoryName() and retreive name
'columns'=>array(
.....
array('name'=>'id','value'=>'$data->getCategoryName()'),
)
public function getCategoryName()
{
$equery= Category::model()->find("id=$this->id");
$cnm=$equery['Category'];
return $cnm;
}

Categories