Yii Framework Forum: Problem With Many_Many Relations - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Problem With Many_Many Relations 'Project', '{{project_goods}}(pid, gid) Rate Topic: -----

#1 User is offline   Ease 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 11
  • Joined: 01-January 12

Posted 15 November 2012 - 09:41 PM

In Goods model:
public function relations() {
return array(
'pg' => array(self::MANY_MANY, 'Project', '{{project_goods}}(pid, gid)'),


$model = Goods::model()->with('pg')->findByPk(2);
echo $model->pg.name;



Use of undefined constant name - assumed 'name'
0

#2 User is offline   waterloomatt 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 545
  • Joined: 09-April 10

Posted 15 November 2012 - 10:16 PM

echo $model->pg->name;

0

#3 User is offline   Ease 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 11
  • Joined: 01-January 12

Posted 15 November 2012 - 10:38 PM

thank you.

echo $model->pg->name


Trying to get property of non-object
0

#4 User is offline   Ease 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 11
  • Joined: 01-January 12

Posted 15 November 2012 - 10:44 PM

$model = Goods::model()->with("pg")->findByPk(2);
$model->dbCriteria->addCondition("pg.pid=2");
echo $model->pg->name;
0

#5 User is offline   Ease 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 11
  • Joined: 01-January 12

Posted 15 November 2012 - 11:31 PM

> Info: If there is no related instance for a relationship, the
corresponding property could be either null or an empty array. For
`BELONGS_TO` and `HAS_ONE` relationships, the result is null; for
`HAS_MANY` and `MANY_MANY`, it is an empty array.
Note that the `HAS_MANY` and `MANY_MANY` relationships return arrays of objects,
you will need to loop through the results before trying to access any properties.
Otherwise, you may receive "Trying to get property of non-object" errors.


hope to help other people
0

#6 User is offline   Ease 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 11
  • Joined: 01-January 12

Posted 16 November 2012 - 12:24 AM

$model->pg[0]->name

it's ok
0

#7 User is offline   waterloomatt 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 545
  • Joined: 09-April 10

Posted 16 November 2012 - 06:56 AM

Yes, since it's a many-many relationship, $model->pg will return an array of Projects.

foreach ($model->pg as $project)
{
    echo $project->name;
}



Matt
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users