我可以在模型函数中使用"::class"表示法吗


Can I use `::class` notation in model functions - Laravel

我正在清理应用程序中的代码。似乎我对::class表示法有误解。

而在我的config/app.php中,声明的提供程序可以从say this:'igaster'laravelTheme'themeServiceProvider',转换为thisigaster'laravelTheme'themeServiceProvider::class,,我不能对模型中的对象执行同样的操作。

例如,我有

public function relateds()
{
    return $this->hasMany('App'Models'Related', 'item_id')->Where('itemkind', '=', 'capacitytypes', 'and')->Where('status', '!=', '2');
}

转换为后

public function relateds()
{
    return $this->hasMany(App'Models'Related::class, 'item_id')->where('itemkind', '=', 'capacitytypes')->where('status', '!=', '2');
}

我收到错误

FatalThrowableError in Model.php line 918: Class 'App'Models'App'Models'Action' not found

这是否意味着我不能在模型中使用符号,或者我做错了什么?

命名空间在这种情况下的行为有点像文件路径,因为当您在整个代码中引用一个时,您可以相对地(相对于当前命名空间(或绝对地(完整命名空间(引用它们。

当你在一个像这样以名称命名的文件中时,如果你省略了前导'字符,那么你是在相对引用。这就是它寻找App'Models'App'Models'Action的原因。

文件config/app.php没有名称空间,因此您提供的任何名称空间都被认为是相对于根名称空间的,因此您不需要前导'字符。

不过,作为参考,你可以在这里做一些事情来解决你的问题。

  • 首先,正如评论中所建议的,你可以在开头放一个',这样它就变成了:

    public function relateds()
    {
        return $this->hasMany('App'Models'Related::class, 'item_id')->where('itemkind', '=', 'capacitytypes')->where('status', '!=', '2');
    }
    
  • 其次,您可以在名称空间声明之后use文件顶部的类,然后在定义关系时省略完整的名称空间,如下所示:

    <?php
    namespace App'Models;
    use App'Models'Related;
    class Action extends Model
    {
        // ...
        public function relateds()
        {
            return $this->hasMany(Related::class, 'item_id')->where('itemkind', '=', 'capacitytypes')->where('status', '!=', '2');
        }
    
  • 最后,更简单地说,由于RelatedAction模型都在同一个App'Models名称空间中,因此在定义关系时可以完全省略该名称空间,而不必在顶部使用use。所以你最终会得到这个:

    public function relateds()
    {
        return $this->hasMany(Related::class, 'item_id')->where('itemkind', '=', 'capacitytypes')->where('status', '!=', '2');
    }