保存Laravel 5.2模型时不存在方法保存 [英] Method save does not exist when saving Laravel 5.2 model

查看:360
本文介绍了保存Laravel 5.2模型时不存在方法保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的表格,其中一个字段是资源".我有一个具有很多资源的Item模型.我正在尝试从表单保存项目及其资源.

I have a simple form, one of the fields is 'resource'. I have an Item model which has many Resources. I'm trying to save both the Item and it's Resource from my form.

Item.php:

public function resource()
{
    return $this->hasMany('App\Resource');
}

public function addResource(Resource $resource)
{
    return $this->resource->save($resource);
}

Resource.php:

Resource.php:

public function item()
{
    return $this->belongsTo('App\Item');
}

我在ItemsController中的保存方法:

My save method in ItemsController:

public function store(CreateItemRequest $request)
{
    //get and save Item
    $item = new Item($request->all());
    Auth::user()->item()->save($item);

    //get and save Resource
    $resource = new Resource(array($request->input('resource')));
    $item->addResource($resource);

    return view('items.index');
}

在Item模型上调用addResource时,出现此错误:

When calling addResource on the Item model, I get this error:

BadMethodCallException in Macroable.php line 81:
Method save does not exist.
in Macroable.php line 81
at Collection->__call('save', array(object(Resource))) in Item.php line 41
at Item->addResource(object(Resource)) in ItemsController.php line 73
at ItemsController->store(object(CreateItemRequest))
at call_user_func_array(array(object(ItemsController), 'store'), array(object(CreateItemRequest))) in Controller.php line 76

我在这个问题上停留了太久了!任何帮助将非常感激.我确定这是一个简单的新手错误...

I've been stuck on this for way too long! Any help would be MUCH appreciated. I'm sure it's a simple newbie mistake...

推荐答案

您的addResource()方法应如下所示:

public function addResource(Resource $resource)
{
    $this->resource()->attach($resource->id);
}

属性 $this->resource将被解析为相关模型的实际实例.如果尚未关联任何模型,它将评估为null. 方法 $this->resource()实际上将返回模型之间存在的关系类型(在这种情况下,它应该返回Illuminate\Database\Eloquent\Relations\HasMany).

The property $this->resource will be resolved to an actual instance of a related model. If no models have yet been related it will evaluate to null. The method $this->resource() will actually return the type of relationship that exists between the models (in this case, it should return Illuminate\Database\Eloquent\Relations\HasMany).

这篇关于保存Laravel 5.2模型时不存在方法保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆