调用laravel关系时避免字符串
问题描述:
This is relationship in model
public function article_children() {
return $this->hasMany(self::class, 'parent_id',self::PRIMARY_KEY);
}
I am calling it with this line
$article_type = ArticleType::with('article_children')->find($id);
My code works nice but what annoys me is that I have to pass method name 'article_children' as string and I am trying to avoid that ...
ideal solution would be
$article_type = ArticleType::with(ArticleType::someReferenceToMethodArticleChildren)->find($id);
So In far far away future I will have option to just CRTL + CLick on that reference and it would lead me directly to relation method in PHP-Storm.
If any one knows the answer how to improve that part of code let me know :)
答
I've got this working. On your ArticleType
model, add:
public static $relChildren = "article_children";
Then when using ::with()
, you can use:
ArticleType::with(ArticleType::$relChildren)->first();
I don't know if that would solve your issue of trying to find the reference via PHPStorm, but this seemed to work for string substituting.