Findall With Relations

Basically, I have two tables:

  1. jobs

+-------------------------+------------------+------+-----+---------+----------------+

| Field                   | Type             | Null | Key | Default | Extra          |

+-------------------------+------------------+------+-----+---------+----------------+

| id                      | int(11)          | NO   | PRI | NULL    | auto_increment |

| site_id                 | int(10)          | NO   |     | NULL    |                |

| name                    | varchar(255)     | NO   |     | NULL    |                |

+-------------------------+------------------+------+-----+---------+----------------+

  1. sites

+------------------+------------------+------+-----+---------+----------------+

| Field            | Type             | Null | Key | Default | Extra          |

+------------------+------------------+------+-----+---------+----------------+

| id               | int(10) unsigned | NO   | PRI | NULL    | auto_increment |

| name             | varchar(50)      | NO   |     | NULL    |                |

| description      | text             | NO   |     | NULL    |                |

+------------------+------------------+------+-----+---------+----------------+

My model is setup with the following…




/**

 * Model for Jobs

 * @return array relational rules.

 */

public function relations()

{

	// NOTE: you may need to adjust the relation name and the related

	// class name for the relations automatically generated below.

	return array(

		'sites' => array(self::HAS_MANY, 'Sites', 'id'),

	);

}




/**

 * Model for Sites

 * @return array relational rules.

 */

public function relations()

{

	// NOTE: you may need to adjust the relation name and the related

	// class name for the relations automatically generated below.

	return array(

		'jobs' => array(self::BELONGS_TO, 'Jobs', 'site_id'),

	);

}

On the controller, I can do…




//$jobs = Jobs::model()->findAll();

$jobs = Jobs::model()->with('sites')->findAll();



And can access the attributes by…


foreach ($jobs as $key => $value) {

	print_r($value->attributes);

}

The problem is, how to access the related sites?

Thanks for the help in advance, I been reading http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-through. But, could not get it to work properly as it is saying I was missing an object?

Solving my question :)


foreach ($jobs as $jk => $jv) {

	print_r($jv->attributes);

	foreach ($jv->sites as $sk => $sv) {

		print_r($sv->attributes);

	}

}

Hi louiemiranda,

I don’t understand the relation between Job and Site.

From the db schema you wrote, it looks like the relation of "Job BELONGS_TO Site" and "Site HAS_MANY Jobs". Is "site_id" in job table not a foreign key to "id" in site table?

[EDIT]

Well, it’s OK if you have solved the problem. :)

(Maybe you have written an outdated schema …)