将一行从一个表复制到另一个表

时间:2017-10-28 14:53:49

标签: php laravel laravel-5 eloquent laravel-5.4

我需要一些帮助,但我找不到答案。我想从一个数据表复制一行到另一个数据表。我的代码是:

public function getClone($id) {
 $item = Post::find($id);
 $clone = $item->replicate();
 unset($clone['name'],$clone['price']);
 $data = json_decode($clone, true);
 Order::create($data);

 $orders = Order::orderBy('price', 'asc')->paginate(5);
 return redirect ('/orders')->with('success', 'Success');
}

我收到了一个错误:

  

"缺少参数1   应用\ HTTP \控制器\ OrdersController :: getClone()"

。 我有两个模型:PostOrder。在试图四处走动并写下这样的东西之后:

public function getClone(Post $id) {
...
}

我收到了另一个错误

  

方法复制不存在。

我的错误在哪里?我做错了什么?也许我应该使用另一个功能?我是否需要用于json_decode的任何其他文件或代码段?

2 个答案:

答案 0 :(得分:1)

首先,确保您的控制器获得 $ id 参数 - 您可以在此处阅读有关路由如何在Laravel中运行的更多信息:https://laravel.com/docs/5.4/routing

Route::get('getClone/{id}','YourController@getClone');

然后,调用包含ID的URL,例如:

localhost:8000/getClone/5

如果您想基于发布对象创建订单对象,则以下代码可以解决问题:

public function getClone($id) {
  // find post with given ID
  $post = Post::findOrFail($id);
  // get all Post attributes
  $data = $post->attributesToArray();
  // remove name and price attributes
  $data = array_except($data, ['name', 'price']);
  // create new Order based on Post's data
  $order = Order::create($data);

  return redirect ('/orders')->with('success', 'Success');

}

答案 1 :(得分:0)

写作

public function getClone(Post $id) 

你告诉脚本这个函数需要来自Post类的变量$ id,所以你可以像这样重写这段代码:

public function getClone(){
  $id = new Post;
}

但是,在您的情况下,这不会有任何意义,因为您需要和整数,您可以从中找到所需的模型。 为了使事情正确,你应该查看你的路线,因为执行这个功能的网址是不正确的,例如,如果你已经定义了这样的路线:

Route::get('getClone/{id}','YourController@getClone');

然后您正在寻找的网址是这样的:

localhost:8000/getClone/5

那样" 5"是帖子的实际ID,如果它是正确的,那么Post :: find($ id)将返回帖子,你将能够复制它,如果没有,它将返回null,你将无法做到如此。

$item = Post::find($id);
if(!$item){
  abort(404)
}

使用此功能将使404页面找不到错误,这意味着ID不正确。