未定义的方法 File::save()(Laravel 模型)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18700772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:24:26  来源:igfitidea点击:

Undefined method File::save() (Laravel model)

phpdatabasemodellaraveleloquent

提问by Bob Dem

I am using Laravel to build a new web project. I am using Eloquent (its ORM) to do all the database related stuff. I have a SQLite database with two tables: 'images' and 'files'. Therefore, I have two models: 'Image.php' (class Image extends Eloquent) and 'File.php' (class File extends Eloquent).

我正在使用 Laravel 构建一个新的 Web 项目。我正在使用 Eloquent(它的 ORM)来做所有与数据库相关的事情。我有一个带有两个表的 SQLite 数据库:“图像”和“文件”。因此,我有两个模型:'Image.php'(类 Image extends Eloquent)和 'File.php'(类 File extends Eloquent)。

According to the documentation I am doing it right. I tried to use the Image model and works perfect. Example of typical use of the model:

根据文档,我做得对。我尝试使用 Image 模型并且效果很好。该模型的典型使用示例:

$image = new Image;
$image->val1 = $val1;
$image->val2 = $val2;
$image->save();

However and for some reason I do not know, the File model is not working as expected. I checked everything: table name, class name, file name, tables... and seems okay for me. I tried to do basically the same:

但是,出于某种我不知道的原因,文件模型没有按预期工作。我检查了所有内容:表名、类名、文件名、表......对我来说似乎没问题。我试图做基本相同的:

$file = new File;
$file->val1 = $val1;
$file->val2 = $val2;
$file->save();

When trying to run this, I get:

尝试运行此程序时,我得到:

Call to undefined method Illuminate\Support\Facades\File::save()

调用未定义的方法 Illuminate\Support\Facades\File::save()

If I do a var_dump() just before the save, it seems that the model is being loaded:

如果我在保存之前执行 var_dump() ,似乎正在加载模型:

object(Illuminate\Support\Facades\File)#133 (4) {
    ["val1"]=> string(8) "abcdef" 
    ["val2"]=> string(10) "ghijkl" 
}

What am I missing here?

我在这里错过了什么?

回答by Gadoma

File is a reserved word in that case because it is the alias for the below facade (defined in /app/config/app.php)

在这种情况下,文件是保留字,因为它是下面外观的别名(在 /app/config/app.php 中定义)

'File' => 'Illuminate\Support\Facades\File',

change the model name to something else, and all of your code should work fine.

将模型名称更改为其他名称,您的所有代码都应该可以正常工作。

回答by Bastin Robin

This problem occurs if you are using any reserved keywords as Model name. For eg:

如果您使用任何保留关键字作为模型名称,则会出现此问题。例如:

Request

要求

File ..etc

文件..等

回答by herohat

For guys who are searching similar problem, remember named of your model class need be singular.

对于正在搜索类似问题的人,请记住您的模型类的命名必须是单数。

class Client extends Eloquent {

protected $table = 'promociones';        

}

then, in your controller:

然后,在您的控制器中:

client = new Client;