将一行从 table 复制到另一行

Copy one row from one table to another

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

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

我得到一个错误:

"Missing argument 1 for App\Http\Controllers\OrdersController::getClone()"

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

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

我又遇到了一个错误

Method replicate does not exist.

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

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

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

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

localhost:8000/getClone/5

如果你想创建一个基于 Post 对象的 Order 对象,下面的代码可以实现:

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');

}

通过写作

public function getClone(Post $id) 

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

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

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

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

那么您正在寻找的 Url 是这样的:

localhost:8000/getClone/5

因此“5”是 post 的实际 ID,如果它正确,则 Post::find($id) 将 return post 并且您将能够复制它,否则,它将 return 为空,您将无法复制。

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

使用这个会出现404 page not found错误,意思是ID不正确。