Laravel致命错误:在Model.php第827行找不到类

4

我对Laravel非常新手。 我尝试在我的代码中使用一个例子,但结果是我得到了一个错误-FatalErrorException in Model.php line 827: Class Category not found

之后,我修改了一行代码并修复了错误。 然而,实际上我不理解错误的原因以及如何修复它。

这是我的代码(当我尝试使用category构建查询时,会出现错误):

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Category;

class Translation extends Model
{
    protected $fillable = array('lang1', 'lang2', 'lang1_code', 'lang2_code', 'category_id', 'created_at', 'updated_at');

    public function category() {
        return $this->belongsTo('Category', 'category_id');
        //return $this->belongsTo('App\Category', 'category_id');
    }        
}

然而,当我修改一行时,就不会出现上述错误:
旧行(错误):return $this->belongsTo('Category', 'category_id'); 新行(无错误):return $this->belongsTo('App\Category', 'category_id');

1
“Category” 和 “Translation” 文件类的路径是什么? - Moppo
检查 Category 的命名空间,但如果保持默认,则应为 $this->belongsTo("App\Category", ...); - Tim Lewis
2个回答

2
在PHP 5.5之前的版本中,你必须添加完整路径。
'App\Category'

自 PHP 5.5 起,class 关键字也用于类名解析。通过使用 ClassName::class,您可以获取包含 ClassName 类的完全限定名称(Fully Qualified Name)的字符串。这在命名空间类中特别有用。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Category;

class Translation extends Model
{
    protected $fillable = array('lang1', 'lang2', 'lang1_code', 'lang2_code', 'category_id', 'created_at', 'updated_at');

    public function category() {
        return $this->belongsTo(Category::class, 'category_id');
    }        
}

2

所有的模型通常存储在App文件夹中。

因此,对于关系,您需要传递完整的模型路径,例如

App\Category

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接