-->

How to use model object in Yii Controller and View

2019-08-28 14:11发布

问题:

I have following method:

public function actionIndex() {

        $companyModel = Company::model()->findAll();          
        $supplierProductModel = SupplierProduct::model()->findAll();

        $this->render('index', array(
            'companyData' => $companyModel,
            'supplierProductData' => $supplierProductModel,
        ));
    }

Here I have passed model objects to render function and want to access these objects in view (Active Relational Type) but when I am accessing its in view its showing error:

Trying to get property of non-object 

view file (index.php)

echo $companyData->name . "\n";
echo $this->companyModel->phone . "\n";
echo $this->companyModel->fax . "\n";
echo $this->companyModel->cell . "\n";

Any help would be appreciated.

回答1:

you need to declare $this->companyModel in your controller/action

$this->companyModel = Company::model()->findByPk($companyId);

with Company::model()->findAll() you get an array of Company-Models you can iterate over in your view-file.

foreach ($companyData as $companyModel) {
    var_dump($companyModel->attributes);
}


回答2:

It is happening becoz of findAll()

findAll() reruns all rows of company table in multidimensional array, so here $companyData is multidimensional Array, now change your code in index like bellow,

        <?php
        foreach ($companyData as $compSub)
        {
            echo $compSub->name . "\n";
            echo $compSub->phone . "\n";
            echo $compSub->fax . "\n";
            echo $compSub->cell . "\n";
        }
        ?>

If you want a company data(single row), change your query like this

         $companyModel = Company::model()->findByPk($id_Of_company); 
         //$companyModel is single dimensional array, it has all the info of a company. 

Send this to view

        $this->render('index', array(
        'companyData' => $companyModel,
        ....................
        ));

Now you can show the data using bellow code

        echo $companyData->name . "\n";
        echo $companyData->phone . "\n";
        echo $companyData->fax . "\n";
        echo $companyData->cell . "\n";


回答3:

You are trying to get all the entries from the database as findAll() returns all data in multidimensional array of objects.If you need all the entries you could iterate over it in the view file and get the results as shown

In the View File do as shown

<?php foreach($companyData as $value){
  echo $vlaue->name . "\n";
  echo $value->phone . "\n";
  echo $value->fax . "\n";
  echo $value->cell . "\n";
 ?>

With this you get all the entries from the table

If you want to get a particular record use condition using Cdbcriteria and pass the object and get the single result