Problem with relations

is it not possible to use findByAttributes on a related model?

The problem is as follows:

The model "Offert":


public function relations()

{

	return array(

	'Div' => array(self::HAS_MANY, 'OffertDiv', 'offertId'),

        );

}

The controller "Offert":

public function actionView($id)


{

	$data['base']=$this->loadModel($id);

	$data['div']=$data['base']->Div;


	$this->renderPartial('/struktur/offert/view',array(

		'data'=>$data,

	),false,true);

}

The view:


<?php $model= $data['div']->findByAttributes(array('divName'=>'divForRegarding')); ?>



Gives this message in the view file:

Fatal error: Call to a member function findByAttributes() on a non-object in C:\XXXXXXX\protected\views\struktur\offertTemplate\offert_base.php on line 23 on line 23

Any ides? or is it not possible to use findByAttributes on a related model?

From the info box in the Working with Databases: Performing Relational Query chapter:

[font="Arial"][size="2"]

[/size][/font]

[font=“Arial”][size=“2”]=> loop through [/size][/font][font=“Arial”][size=“2”]$data[‘div’][/size][/font]

[font=“Arial”][size=“2”]I also suggest to move the query from the view to the controller cause it’s better to have as less logic/sql related stuff in views as possible.[/size][/font]

aha… thank you!

But how do i loop loop through on


<?php $model= $data['div']->findByAttributes(array('divName'=>'divForRegarding')); ?>

sorry, im new on Yii…

Is the above correct?

Then you don’t have to use findByAttributes.




    $data['base'] = $this->loadModel($id);

    $data['div'] = array();

    foreach($data['base']->Div as $div)

    {

        $data['div'][$div->divName] = $div;

    }

    $this->renderPartial('/struktur/offert/view',array(

        'data'=>$data,

    ),false,true);


...

// in view

    if (isset($data['div']['divForRegarding']))

    {

        $model = $data['div']['divForRegarding']:

        ...

    }



Or, you could define HAS_ONE relation for it. But I don’t know if it’s preferable or not.

As kokomo pointed out, you can’t apply dynamic filters to Yii’s AR relations.

I believe the best solution would be to add a method to your model that completes this relation.




public function getDiv($attributes=array())

{

    if ($this->isNewRecord) {

        return array();

    }

    $attributes['offertId'] = $this->primaryKey;

    return OffertDiv::model()->findAllByAttributes($attributes);

}



You can use this method with:




$arrayOfDiv = $model->getDiv();

$arrayOfDiv = $model->Div; // magic attribute, same as above (replaces the relation)

$arrayOfDiv = $model->getDiv(array('divName'=>'divForRegarding')); // what you wanted