Can't get property of model in case of chained relationships

Started with Yii just recently and everything went fine until I bumped into this one…

I have this kind of relations:

MODEL belongs_to PRODUCT belongs_to SUPPLIER

Relation in product class:


'supplier' => array(self::BELONGS_TO, 'Supplier', 'suppliers_idsuppliers'),

Relation in model class:


'product' => array(self::BELONGS_TO, 'Product', 'products_idproducts'),

This works when I try to access supplier’s name in model’s view:


<?php echo $model->product->supplier->name; ?>

However, when I try to get supplier’s name for some CGridView stuff like this:




	/**

	 * Gets supplier name

	 */

	public function getSupplierName()

	{

		if ($this->_supplierName === null && $this->product->supplier !== null)

		{

			$this->_supplierName = $this->product->supplier->name;

		}

		return $this->_supplierName;

	}



it fails with the following error:


Trying to get property of non-object

What am I missing here?

are both relations defined in one and the same model?

Hi bettor,

No, sorry for not making this clear enough.

One of them is in "Product" model (referring to suppliers), another one in "Productmodel" model (referring to products).

Does anyone have any ideas?

Hi,

What exactly is throwing the error, $this, $this->product, or $this->product->supplier?

I think you can pinpoint it by adding some tracing code.

It comes from the getter located in the MODEL class:




/**

 * Gets supplier name

 */

public function getSupplierName()

{

	if ($this->_supplierName === null && $this->product->supplier !== null)

	{

		$this->_supplierName = $this->product->supplier->name;

	}

	return $this->_supplierName;

}



So it’s $this->product->supplier and/or it’s property ‘name’ that causes problems.

Any ideas? This really drives me crazy…

Could you try this to pinpoint the error?




public function getSupplierName()

{

	Yii::trace("getSupplierName ... entered");

	if ($this->_supplierName === null)

	{

		Yii::trace("getSupplierName ... _supplierName is null");

		if ($this->product !== null)

		{

			Yii::trace("getSupplierName ... product is not null");

			if ($this->product->supplier !== null)

			{

				Yii::trace("getSupplierName ... supplier is not null");

				$this->_supplierName = $this->product->supplier->name;

				Yii::trace("getSupplierName ... name set");

			}

		}

	}

	return $this->_supplierName;

}



Ah, just a thoguth, but could you show us your CGridView code where you are showing this?

I’m afraid you have wrong syntax to show this ‘supplierName’ …

Something like the following should be the right syntax …




    array(

        'label' => 'Supplier Name',

        'value' => '$data->supplierName',

    ),