Fatal error after adding ->with(...) to ->findAll() - Relational Active Record

Hello

I’ve got 3 database tables:

  • A

  • B

  • C

Relationships:

  • A has many B.

  • A has many C.

  • B belongs to A.

  • C belongs to A.

In [font=“Courier New”]AController[/font]'s [font=“Courier New”]actionHome($id)[/font], I’m retrieving the single row of [font=“Courier New”]A[/font] from the database. Just like the default [font=“Courier New”]actionView($id)[/font].

In my View for [font="Courier New"]actionHome()[/font], I also list all instances of [font="Courier New"]B[/font] and [font="Courier New"]C[/font] that belong to that [font="Courier New"]A[/font].




  public function actionHome($id)

  {

    $this->render('home', array('a' => A::model()->findByPk($id)));

  }



In [font=“Courier New”]actionHome()[/font], I want to use eager loading of [font=“Courier New”]A[/font]'s relationships.

But, when I add [font="Courier New"]with()[/font] to the [font="Courier New"]findByPk()[/font] function, I immediately get a fatal error.




  public function actionHome($id)

  {

    $this->render('home', array('a' => A::model()->with('bs','cs')->findByPk($id)));

  }



Fatal error: Call to a member function label() on a non-object in my [font="Courier New"]home.php[/font] view file.

[font="Courier New"]label()[/font] is a public static function I have within my [font="Courier New"]A[/font] model class.

So, since I’ve added eager loading, this causes the function to be unavailable.

Can someone please assist?

Why would this function no longer be available?

Hi,

please provide a code part where [b]label/b is invoked.

[font="Courier New"]label()[/font] is involved in my view home.php like so:




<?php


/*

 * Breadcrumbs

 * ------------

 */


$this->breadcrumbs = array(

  CHtml::encode($a->label(2)) => array('index'),

  CHtml::encode($a->name),

);

?>

[font="Courier New"]label()[/font] is defined as follows in my model:


public static function label($n = 1) 

{

  if ( $n == 0 ) $n = 1;

  return Yii::t('app', 'A|As', $n);

}

If I comment-out the call the [font="Courier New"]label()[/font] within the view, then the next line just triggers a fatal error too,… that "name" is not a property of non-object.

Obviously, for some reason, [font="Courier New"]$a[/font] is no longer an object.

To prevent issues like the described one, static methods should be called in static context:




$this->breadcrumbs = array(

  CHtml::encode(A::label(2)) => array('index'),

  CHtml::encode($a->name),

);