need help with relations()

Hi I have 3 table:




#table1

table_Bookmark

member_id

food_id






#table2

table_food

id

name




#table3

table_member

id

first_name

last_name

so I use this script to make these tables related:




    public function relations(){

        return array(

            'members' => array(self::HAS_MANY,'Members','id'),

            'foods' => array(self::HAS_MANY,'Foods','id')

        );

    }



in controller





    public function actionList(){

        $model = Bookmark::model()->with('foods')->findAll('member_id = '. Yii::app()->user->getId());

        

        $this->render('watchlist',array(

                'model' => $model

            ));

    }



in view


foreach($model as $result){

echo $result->foods->name;

}

but the view is displayed none. where is the wrong. please help me…

I still confused to make relationing datbase with this.

thanks





foreach($model as $result){

  foreach($result->foods as $food){

    echo $food->name;

}



/Tommy

OK I will try :slight_smile: thank for reply tri

Hi tri, it is still doesn’t work

I have Bookmark table that only store (member_id and food_id).

and I want display record that containts member_id = 1,

how to do this? are the relations that i declared above is correct? because I have try it much but still failed, so I confused…

please help me tri or maybe someone :slight_smile:

Thanks

You should use the foreign key in the relationship declaration.

‘foods’ => array(self::HAS_MANY,‘Foods’,‘food_id’)

Edit:

Sorry, considering only the case that table_bookmark HAS_MANY table_food (table_food HAS_ONE table_bookmark), you should have a foreign key "bookmark_id" in table_food.




  'foods' => array(self::HAS_MANY,'Foods','bookmark_id')



You don’t mention why you included table_member in your question. Do you want to construct a MANY_TO_MANY relationship?

Edit2:

I guess you probably want to join both tables using with(foods, members) and change the relationship to HAS_ONE




  'members' => array(self::HAS_ONE,'Members','member_id'),



/Tommy

hi tri, thanks for your reply.

the case is: I want displaying foods that bookmarked by member.

Yes I want to make MANY_TO_MANY relations.

I have attached database screenshoot.

I still confused how to make the relationship works.

Thanks

According to the diagram I think this should work (located in your Bookmark model, of course)




    public function relations(){

        return array(

            'members' => array(self::BELONGS_TO,'Members','member_id'),

            'foods' => array(self::BELONGS_TO,'Foods','food_id')

        );

    }



Now your original view code should work (BELONGS_TO doesn’t return an array).

(beware, not tested)

/Tommy

OK tri, thanks for your reply. I will try :slight_smile: