简体   繁体   中英

Copy one row from one table to another

I need a little help and I can't find an answer. I would like to replicate a row from one data table to another. My code is:

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

and i got an error :

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

. I have two models: Post and Order . After trying to walk around and write something like this:

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

I got another error

Method replicate does not exist.

Where's my mistake? What wrong have i done? Maybe i should use another function? Do i need any additional file or code snippet used for json_decode ?

First of all, make sure your controller gets the $id parameter - you can read more about how routing works in Laravel here: https://laravel.com/docs/5.4/routing

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

Then, call the URL that contains the ID, eg:

localhost:8000/getClone/5

If you want to create an Order object based on a Post object, the following code will do the trick:

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

}

By writing

public function getClone(Post $id) 

you are telling the script that this function needs a variable $id from class Post, so you can rewrite this code like this :

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

However, in your case this does not make any sence, because you need and integer, from which you can find the required model. To make things correct, you should look at your routes, because the url that executes this function is not correct, for example, if you have defined a route like this :

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

then the Url you are looking for is something like this :

localhost:8000/getClone/5

So that "5" is the actual ID of the post, and if its correct, then Post::find($id) will return the post and you will be able to replicate it, if not, it will return null and you will not be able to do so.

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

Using this will make a 404 page not found error, meaning that the ID is incorrect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM