From MySQL to Active Record, how?

I have this query as I would usually write it for MySQL:

$sql = 'select, vehiculo_marca from vehiculo_marca, anuncio, usuario ';

$sql .= 'left join anuncio on anuncio.vehiculo_marca_id = anuncio.marca_id ';

$sql .= 'left join usuario on = anuncio.usuario_id ';

$sql .= 'where usuario.activo = 1 and anuncio.activo = 1 and vehiculo_marca.activo = 1';

if ($_POST['estado'] > 0) {

	$sql .= ' and anuncio.estado_id = '.$_POST['estado'];


The tables are related:

vehiculo_marca ONE TO MANY anuncio

usuario ONE TO MANY anuncio

How would I write it for Active Record?


read up on relational AR in the guide. Where you will learn how to set up relations between your models.

You will have to create models for vehiculo_marca, aununcio and usario and create the relationships between them.

It should be very straightforward

If you read the guide you had used CLI tool to generate your model file.

It usually generate relations() by itself. Check if everything is Ok with yours FKs in DB.

Inside you controller actions you are expected to type something like that:

$model = model::model()->findAll();

Try getting along with API (

Well, I opted to use findAllBySql

$resultado = vehiculo_marca::model()->findAllBySql($q);

I don’t understand ActiveRecord, anyone knows of a good ActiveRecord tutorial?