Reputation: 11
This is the relation I have in my model
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
public function getTaskCreatedBy()
{
return $this->hasOne(User::className(), ['id' => 'taskCreatedBy']);
}
And now i want to use taskcreatedby
and get fullname
of user which i have done like this:
Created By:<?php echo $model->taskCreatedBy->fullname?>
But, I am getting error saying :Trying to get property of non-object
Upvotes: 1
Views: 98
Reputation: 199
So you have 2 relations connecting to this model/table. 1. A User table connects to the user_id field/database column in this model. 2. A TaskCreatedBy table connects to the taskCreatedBy field in this model.
What is this model's table's name? Found in your tableName function.
public static function tableName()
{
return '???????????????';
}
Understanding the below code:
['id' => 'taskCreatedBy']
can be summarised as follows:
['fieldname called 'id' in foreign model table called TaskCreatedBy' => 'fieldname called taskCreatedBy in current model table' ie. the name of the foreign key field/database column that is in your current model table ...the name of this model/file/table which you have not given us]
Verify that 'taskCreatedBy' , as in the above snippet of code, is the actual name of the field in your current model table ie. the table belonging to the file that the above code is in.
I would simplify your table names to avoid getting uppercase and lowercase issues when having to type your relation code
<?php echo $model->taskCreatedBy->fullname?>
and also not use a field/database column like taskCreatedBy which is very similar to the table name TaskCreatedBy. My suggestion is that you rename your field taskCreatedBy in your table TaskCreatedBy to taskcreatedby_id.
In the above snippet of code
['id' => 'taskCreatedBy']
taskCreatedBy should be in lowercase and correspond to the actual field/database column name preferably taskcreatedby_id that exists in your current model/table.
Upvotes: 0
Reputation: 133400
check the real column name could be that your db colum name is not taskCreatedBy but somethings different eg: (or others column name)
public function getTaskCreatedBy()
{
return $this->hasOne(User::className(), ['id' => 'task_created_by']);
}
Upvotes: 2