jkchan
(Jackieochan)
March 11, 2014, 12:23pm
1
Hi,
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.
konapaz
(Konapaz)
March 11, 2014, 3:41pm
3
Hi
If you want the locates of the specific product then
$product = Product::model()->findByPk(1);
var_dump($product->productlocales);
but why use ProductLocale to find the product and then find the relations (or productlocales) ?
Please give us more details what you want to do
jkchan
(Jackieochan)
March 12, 2014, 2:51am
4
Hello KonApaz,
I want to get all the related products to a single product.
For example,
products table
id brand
1 brand_1
2 brand_1
product_locales
id product_id name locale
1 1 sample_1 en
2 2 sample_2 en
3 2 sample_2 zh
product_relations
id product_id related_id
1 1 2
So I want to get the related product_locale of the pkID(1).
So when I call
$product = ProductLocale::model()->findByPk(1);
I want to output sample_2-en and sample_2-zh as well.
Thank you for the help, I am really new to this.
konapaz
(Konapaz)
March 13, 2014, 11:05am
5
jkchan:
Hello KonApaz,
I want to get all the related products to a single product.
For example,
products table
id brand
1 brand_1
2 brand_1
product_locales
id product_id name locale
1 1 sample_1 en
2 2 sample_2 en
3 2 sample_2 zh
product_relations
id product_id related_id
1 1 2
So I want to get the related product_locale of the pkID(1).
So when I call
$product = ProductLocale::model()->findByPk(1);
I want to output sample_2-en and sample_2-zh as well.
Thank you for the help, I am really new to this.
using
$product = ProductLocale::model()->findByPk(1);
var_dump($product->product->relations);
You get all relation products (in your case an array with one element)
"1 1 sample_1 en" belongs "1 brand_1" that has only one relation "1 1 2"
So to get the related product from relation model you have to
Product::model()->findByPk($product->product->relations[0]->related_id);