简体   繁体   中英

Adding data from a column to another table's column Laravel 5.2

So, I want to store some products to the product table. I managed that. But now I want to attach a user id to each product, so it can correspond to a different user.

As for now, I have tried this, but it doesn't seem to work:

public function store(){
    $product = Request::all();
    $product = Product::create($product);
    $user = User::whereId(Request::input('user'))->first();
    $product->users()->attach($user);
    return redirect()->route('products');
}

The relationship between users and products is this: a user_id column in products table is foreign key and references to the id on users table

You can use relation methods to save related objects as:

Assuming relation name in User model is products

public function store() {
  $product_array = Request::all();

  $product = Auth::user()->products()->create($product_array);

  return redirect()->route('products');
}

Here the create method will automatically add the appropriate user_id value to the new Product model.

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