简体   繁体   English

将数据从一列添加到另一个表的列Laravel 5.2

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

So, I want to store some products to the product table. 因此,我想将一些产品存储到product表中。 I managed that. 我做到了 But now I want to attach a user id to each product, so it can correspond to a different user. 但是现在我想为每个产品附加一个user id ,以便它可以对应于另一个用户。

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 usersproducts之间的关系是这样的: products表中的user_id列是foreign key并且对users表中的id引用

You can use relation methods to save related objects as: 您可以使用关系方法将相关对象另存为:

Assuming relation name in User model is products 假设User模型中的关系名称是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. 在这里, create方法将自动将适当的user_id值添加到新的Product模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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