Reputation: 1
I have a user_detail table
CREATE TABLE `user_detail` (
`id` int(11) unsigned NOT NULL,
`userID` int(11) NOT NULL,
`name` varchar(20) NOT NULL,
);
I want to retrieve the value of user_detail
.name
in main.php to display the loggedin user's name.
in UserDelail class I added a getter:
public function getFullName()
{
return $this->hasOne(UserDetail::className(), ['userID' => Yii::$app->user->identity->id]);
}
In main.php I have <?= UserDetail::getFullName()->name ?>
and I am getting: Calling unknown method: yii\web\View::hasOne()
What is wrong here? and how can i correct that?
Thank you
Upvotes: 0
Views: 1011
Reputation: 1
I was able to solve it in the following way:
public function getFullName()
{
$userInfo = UserDetail::findOne(['userID' => Yii::$app->user->identity->id]);
return $userInfo->first . ' ' . substr($userInfo->middle, 0,1) . '. ' . $userInfo->last;
}
I do not like this solution but it is what I have for now in wait for a better solution.
Upvotes: 0
Reputation: 1343
You haven't address the namepsace correctly in either your View
file or your Model class
Please add something like use app\models\UserDetail
at the top of your view file.
Upvotes: 0
Reputation: 539
edit.
To get current logged user data u can simply:
Yii::$app->user->identity->id
Yii::$app->user->identity->name
And u can do it wherever: directly in the view, in controller, model and so on...
Why u are making realtion to ClassX in ClassX.
The whole idea of realtions is to connect ClassX to ClassY.
You should add in for example model/Project:
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'userId']);
}
And the and in the model/User:
public function getProject() {
return $this->hasMany(Project::className(), ['userId' => 'id' ] );
}
Now when u want to throw out somedata from User table in Project/index for example you just (in model/project):
public function getUserName() {
return $this->user ? $this->user->username : '- no user type-';
}
Next in the project view/projectIndex:
'<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
'userName',
],]);
Or:
<?php $new = new Project; ?>
<?= $new->getUserName(); ?>
It all depends where and what for, you want to throw data.
Upvotes: 1