保存 Laravel 5.2 模型时方法保存不存在
Method save does not exist when saving Laravel 5.2 model
我有一个简单的表格,其中一个字段是'resource'。我有一个有很多资源的项目模型。我正在尝试从我的表单中保存项目及其资源。
Item.php:
public function resource()
{
return $this->hasMany('App\Resource');
}
public function addResource(Resource $resource)
{
return $this->resource->save($resource);
}
Resource.php:
public function item()
{
return $this->belongsTo('App\Item');
}
我在 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 时,出现此错误:
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
我已经坚持这个太久了!任何帮助将非常感激。我确定这是一个简单的新手错误...
您的 addResource()
方法应如下所示:
public function addResource(Resource $resource)
{
$this->resource()->attach($resource->id);
}
属性$this->resource
将解析为相关模型的实际实例。如果尚未关联任何模型,它将评估为 null
。 方法 $this->resource()
实际上return模型之间存在的关系类型(在这种情况下,它应该return Illuminate\Database\Eloquent\Relations\HasMany
).
我有一个简单的表格,其中一个字段是'resource'。我有一个有很多资源的项目模型。我正在尝试从我的表单中保存项目及其资源。
Item.php:
public function resource()
{
return $this->hasMany('App\Resource');
}
public function addResource(Resource $resource)
{
return $this->resource->save($resource);
}
Resource.php:
public function item()
{
return $this->belongsTo('App\Item');
}
我在 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 时,出现此错误:
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
我已经坚持这个太久了!任何帮助将非常感激。我确定这是一个简单的新手错误...
您的 addResource()
方法应如下所示:
public function addResource(Resource $resource)
{
$this->resource()->attach($resource->id);
}
属性$this->resource
将解析为相关模型的实际实例。如果尚未关联任何模型,它将评估为 null
。 方法 $this->resource()
实际上return模型之间存在的关系类型(在这种情况下,它应该return Illuminate\Database\Eloquent\Relations\HasMany
).