我在Laravel中保存模型时出错。 '在非对象上调用成员函数getKey()'

时间:2015-02-17 09:48:18

标签: laravel laravel-4 eloquent

我尝试通过以下代码在DB中保存我的对象:

$preview = new ProjectProductPreview();
$preview->user_id = $user_id;
$preview->path = $preview_url;
$preview->type = $type;
$preview->project_product_id = $product_id;
$preview->save();  

我得到了奇怪的错误。调用save()方法时会发生此错误。 我检查了我的laravel日志,有这个错误。我可以精确地调试它,因为在这种情况下,错误堆栈只有两个位置

[2015-02-17 09:37:30] production.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to a member function getKey() on a non-object' in /var/www/erp/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Collection.php:133
    Stack trace:
    #0 [internal function]: Illuminate\Exception\Handler->handleShutdown()
    #1 {main} [] []

我的模型看起来像:

class ProjectProductPreview extends BaseModel {

    protected $table = 'project_products_preview';


    public function user() {
        return $this->belongsTo('User');
    }

    public function project_product() {
        return $this->belongsTo('ProjectProduct', 'project_product_id');
    }

    public function projectProduct()
    {
        return $this->belongsTo('ProjectProduct', 'project_product_id');
    }

    public function message() {
        return $this->belongsToMany('Message');
    }

    public function getThumb() {
        $path = $this->path;
        $thumb_path = str_replace('.jpg', '_70.jpg', $path);
        return $thumb_path;
    }

    public function fullPath() {
        return public_path($this->path);
    }

    public function getPath()
    {
        return $this->path;
    }

    public function getUrlAttribute() {
        $product_id = $this->project_product_id;

        return '/product/' . $product_id . '#' . $this->id;
    }

    public function isAccepted()
    {
        if($this->accepted==1){
            return true;
        }

        return false;
    }

    public function accept()
    {
        ProjectProductPreview::where('project_product_id',$this->project_product_id)->update(array('accepted'=>0));
        $this->accepted=1;
        $this->save();

        Event::fire('project_product_preview.accepted', array($this));
    }

    public function acceptRemove()
    {
        $this->accepted=0;
        $this->save();

        Event::fire('project_product_preview.remove_accept', array($this));
    }

}

1 个答案:

答案 0 :(得分:0)

我对此不太确定,但我认为这一行

$preview->project_product_id = $product_id;

导致问题。您与ProjectProduct有关系,所以您可能想做某事。就像那样:

$preview->projectProduct()->associate(ProjectProduct::find($product_id));

the laravel docs on inserting models。另请注意,您与ProjectProduct有两个相同的实际情况,这可能会导致意外行为。至少有一个是超级的。

// one can be removed
//public function project_product() {
//    return $this->belongsTo('ProjectProduct', 'project_product_id');
//}

public function projectProduct()
{
    return $this->belongsTo('ProjectProduct', 'project_product_id');
}