Relations Problem

dont know whats happen , but i have 2 models:

Reserva

ReservaState

in Reserva i have

‘states’ => array(self::HAS_ONE, ‘ReservaState’, ‘id’),

in ReservaState

‘reservas’ => array(self::HAS_MANY,‘Reserva’,‘reserva_state’)

$model = Reserva::model()->with(‘states’, ‘cliente’,‘precos’)->findByPk($id);

But always get null. on $model->states

Reserva have one reservaState

need help

I see you have to have fk in relationship


'states' => array(self::HAS_ONE, 'ReservaState', 'id'), // use your fk 


'reservas' => array(self::HAS_MANY,'Reserva','reserva_state') // same here use your fk 

if you can upload your database schema then i might be able to tell you what exactly to change

thanks , here schema of tables

CREATE TABLE reserva_state (

id int(11) NOT NULL AUTO_INCREMENT,

state varchar(25) NOT NULL,

PRIMARY KEY (id)

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE reserva (

id int(11) NOT NULL AUTO_INCREMENT,

n_prereserva int(11) DEFAULT NULL,

reservado bit(1) DEFAULT NULL,

valor varchar(45) DEFAULT NULL,

n_cheque varchar(45) DEFAULT NULL,

valorSinal varchar(45) DEFAULT NULL,

idcliente int(11) NOT NULL,

idpreco int(11) NOT NULL,

tipopagamento int(11) DEFAULT NULL,

n_pagamento int(11) DEFAULT NULL,

reserva_state int(11) NOT NULL,

data timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,

user varchar(50) NOT NULL,

PRIMARY KEY (id)

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

just want to show the state description and not the state id

change this

‘states’ => array(self::HAS_ONE, ‘ReservaState’, ‘id’)

to

‘states’ => array(self::HAS_ONE, ‘ReservaState’, ‘reserva_state’)

Umm, it should be a simple 1:N relation … 1 for ReservaState and N for Reserva …

"A ReservaState has many Reservas" and "A Reserva belongs to ReservaState".

It is a pair of "HAS_MANY" and "BELONGS_TO" sharing the same FK.

in Reserva




'states' => array(self::BELONGS_TO, 'ReservaState', 'reserva_state'),



in ReservaState




'reservas' => array(self::HAS_MANY, 'Reserva','reserva_state')



Don’t be confused by the name of “HAS_ONE”.

http://www.yiiframework.com/wiki/181/relations-belongs_to-versus-has_one

Samdark. 1k thanks.

By the way, lets say if i want to relate to another model/table that is not directly related. ex: relate to owner that have a relation with house that have a relation to reserva.

Can i relate directly to owner in reserva.

Thanks again and hope i explain clearly.

I’m not samdark, but yes, you can use a relation’s relation.

Let’s say, if a->b and b->c, then we can use a->b->c.

ok softark. thanks again