2017-01-13 08:51
浏览 34

将数据从列添加到另一个表的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();
    return redirect()->route('products');

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

图片转代码服务由CSDN问答提供 功能建议

因此,我想将一些产品存储到 product 表中。 我做到了。 但是现在我想为每个产品附加一个用户ID ,因此它可以对应不同的用户。

至于现在,我已经尝试了这个,但是 它似乎不起作用:

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

users 之间的关系 >产品是这样的: products 表中的 user_id 列是外键并且引用 id 用户

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanpo8329 2017-01-13 08:59

    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.

    打赏 评论

相关推荐 更多相似问题