Laravel非静态方法问题


Laravel Non-static method issue

具有以下模型:

news.php

class News extends Aware {
    public static $table = 'noticia';
    public static $key = 'idnoticia';
    public static $timestamps = false;
    public static $rules = array(
        'titulo' => 'required',
        'subtitulo' => 'required',
    );
    public function images()
    {
        return $this->has_many('Image');
    }
}

image.php

class Image extends Aware {
    public static $timestamps = true;
    public static $rules = array(
        'unique_name' => 'required',
        'original_name' => 'required',
        'location' => 'required',
        'news_id' => 'required',
    );
    public function news()
    {
        return $this->belongs_to('News');
    }
}

然后在控制器中执行以下操作:

$image = new Image(array(
    'unique_name' => $fileName,
    'original_name' => $file['file']['name'],
    'location' => $directory.$fileName,
    'news_id' => $news_id,
));
News::images()->insert($image);

我一直得到以下错误信息:

非静态方法News::images()不应该静态调用,假设$this来自不兼容的上下文

你知道我做错了什么吗?

设置public static function images()似乎不需要,因为刷新后我得到一个错误说

$this不在对象上下文中

Gordon说通过做News::images()->insert($image);,我做了一个静态调用,但我就是这样做的

您缺少一些步骤。

图片属于新闻,但是你没有引用你想要更新的新闻文章。
你可能想这样做:

$image = new Image(array(...));
$news = News::find($news_id);
$news->images()->insert($image);

更多文档

您在称为static ally的函数中使用$this。那是不可能的。

$this只有在使用new创建实例后才可用。

如果你打开严格模式,你会得到另一个错误,即images不是一个静态函数,因此不应该静态调用。

问题在News::images(),而不是在images()->insert($image);

$this只能在对象实例中使用。Class::method()调用指定类的静态方法。

在你的例子中,你把两者混合了。

images的函数定义是一个对象实例:

public function images()
{
    return $this->has_many('Image');
}

你以静态方法调用它:

News::images()->insert($image);

需要实例化News类,或者修改images方法以支持静态调用。