Show LEFT JOIN result

Here is my code.

ProfileController.php





use app\models\Store;


public function actionIndex()

{

  $storeInfo = $this->findStoreInfo(Yii::$app->user->identity->id);

  return $this->render('index',['storeModel' => $storeInfo]);		

}


protected function findStoreInfo($uid)

{

  if (($model = Store::getStoreInfoByUserId($uid)) !== null)

    return $model;

  else

    throw new NotFoundHttpException('The requested page does not exist.');

}



Store.php




public static function getStoreInfoByUserId($uid)

{

  $storeInfo = self::find()->select('my_store.*, my_rank.rank_name')

			->leftJoin('my_rank','my_store.store_rank = my_rank.id')

			->where(['my_store.uid'=> $uid])->one();

  return $storeInfo;

}



profile/index.php




<?= Html::encode($storeModel->rank_name) ?>



Although I see the query is showing correctly in Yii debug tool,

but when I’m trying to echo $storeModel->rank_name,

it show "Getting unknown property: app\models\Store::rank_name"

Working fine for echo my_store table data.

Highly appreciated for any help.

Thanks!

Store, an Active Record model, has all the columns of my_store table as its properties. So you can access ‘store_name’ column of my_store table by the notation of ‘$storeModel->store_name’ for instance.

But, it doesn’t automatically have a property for related table.

[sql]

select my_store.*, my_rank.rank_name from my_store left join my_rank …

[/sql]

The sql above will be executed as you expect. But Store model has no place for rank_name. So the ‘rank_name’ will be abandoned.

The expected way you should follow is to use Relational Active Record.

See Guide > Working with Databases > Active Record > Working with Relational Data

http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#relational-data

Thank you softark for your reply.

I did try your solution as shown below:

Store.php




public function getStoreRank()

{

  return $this->hasOne(StoreRank::className(),['id'=>'store_rank']);

}


public static function getStoreInfoByUserId($uid)

{

  $storeInfo = self::find()->select('my_store.*, my_rank.rank_name')

			->leftJoin('my_rank','my_store.store_rank = my_rank.id')

			->where(['my_store.uid'=> $uid])->one();

  $storeInfo = $storeInfo->storeRank;

  return $storeInfo;

}



StoreRank.php




public function getStore()

{

  return $this->hasMany(Store::className(),['store_rank'=>'id']);

}



However,

I am able to echo rank_name now, but not store_name.

I want to echo both rank_name and store_name with $storeModel.

Am I missing out anything?




public static function getStoreInfoByUserId($uid)

{

  $storeInfo = self::find()->with('storeRank')

			->where(['my_store.uid'=> $uid])->one();

  return $storeInfo;

}



And in the view:




    <p>Store Name = <?= $storeInfo->store_name ?></p>

    <p>Store Rank = <?= $storeInfo->storeRank->rank_name ?></p>



Thank you for your time, softark!

I got what I want ;)