[英]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 users
和products
之间的关系是这样的: 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.