2

具有以下型号:

新闻.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');
    }
}

图像.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);

我不断收到以下错误消息:

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

任何想法我做错了什么?

public static function images()似乎不需要设置,因为刷新后我收到一条错误消息

$this 不在对象上下文中时

戈登说News::images()->insert($image);我这样做是在做一个静态调用,但这就是锯做的方式

4

3 回答 3

3

You're using $this in a function that is called statically. That's not possible.

$this becomes available only after you create an instance with new.

If you turn on strict mode you will get another error, namely that images is not a static function and thus shouldn't be called statically.

The problem is in News::images(), not in images()->insert($image);

于 2013-01-02T17:48:38.030 回答
3

您缺少一些步骤。

图片属于新闻,但您没有引用要更新的新闻帖子。
你可能想做:

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

更多在文档中。

于 2013-01-02T18:25:51.453 回答
1

$this can only be used within an object instance. Class::method() calls a static method of the specified class.

In your case, you mixed both.

Your function definition for images is for an object instance:

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

You are calling it as a static method:

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

The News class would need to be instantiated or the images method be modified to support static calls.

于 2013-01-02T17:50:49.990 回答