Yes, the default naming from Gii for relations can be quite generic and not very descriptive, especially when you have multiple relations to the same table but with different foreign keys (created_by, updated_by, etc.).
Problem Recap
In your example, Gii generates:
public function getAppNews()
{
return $this->hasMany(AppNews::class, ['created_by' => 'id']);
}
public function getAppNews0()
{
return $this->hasMany(AppNews::class, ['updated_by' => 'id']);
}
getAppNews() and getAppNews0() are not very clear names for these relations.
How to fix this?
1. Manually Rename the Relations in Your Model
The quickest and most common solution is:
- Rename
getAppNews() to something like getCreatedAppNews() or getNewsCreatedByUser()
- Rename
getAppNews0() to getUpdatedAppNews() or getNewsUpdatedByUser()
Example:
public function getCreatedAppNews()
{
return $this->hasMany(AppNews::class, ['created_by' => 'id']);
}
public function getUpdatedAppNews()
{
return $this->hasMany(AppNews::class, ['updated_by' => 'id']);
}
You can also change the PHPDoc blocks accordingly for clarity.
2. Customize Gii's Generated Code Using the "Relations" Callback
You can customize the code Gii generates by changing the relation names manually after generation or customizing the code templates Gii uses.
-
Modify Gii Templates: Gii uses templates like activeRecord.php that you can override in your project to change how relation methods are named/generated.
-
You can set up a custom Gii template where you specify rules for relation names, e.g.:
- If foreign key column contains
created_by, relation method could be named getCreated[TableName].
- If foreign key column contains
updated_by, use getUpdated[TableName].
3. Use relations() method or relationName comments (in older Yii versions)
In Yii2, Gii relies on database schema and foreign key names, so it can’t guess good relation names automatically.
You can manually write or rename relation functions - Gii is a scaffold that requires some following edits for fine-tuning.
Summary:
- The best practice is to manually rename relations after generation to meaningful names.
- You can also create or configure custom Gii templates to generate better names.
- Consider naming your foreign keys to include meaningful info, as Gii sometimes takes cues from FK column names.
Example final right way:
/**
* Gets query for news this user created.
*
* @return \yii\db\ActiveQuery|AppNewsQuery
*/
public function getCreatedAppNews()
{
return $this->hasMany(AppNews::class, ['created_by' => 'id']);
}
/**
* Gets query for news this user updated.
*
* @return \yii\db\ActiveQuery|AppNewsQuery
*/
public function getUpdatedAppNews()
{
return $this->hasMany(AppNews::class, ['updated_by' => 'id']);
}
This naming is descriptive, clear, and better for readability and maintainability.