我又来了,但现在我需要你的一些帮助,我有一些版本的购物车,整个想法就是当我点击产品按钮时数据库要用用户信息更新( id)订购产品(id)。首先我使用信息(id,product_name,price)创建订单表,其他表是users表(id,user_name)和最终表user_order表(id,user_id,order_id);
之后我制作了两个模型,一个是产品的订单模型,第二个是用户模型。我想要的关系是这两种模式之间的关系。
用户模型功能:
public function orders(){
return $this->belongsToMany('App\Orders', 'user_order', 'user_id', 'order_id');
// return $this->belongsToMany('App\Orders');
}
订单模型功能:
public function users(){
return $this->belongsToMany('App\User', 'user_order', 'order_id', 'user_id');
//return $this->belongsToMany('App\User');
}
这是我使用提交按钮显示所有产品的主要HTML:
<div class="row">
@foreach($orders as $order)
<div class="col-sm-4 col-lg-4 col-md-4">
<div class="thumbnail">
<img src="http://placehold.it/320x150" alt="">
<div class="caption">
<h4 class="pull-right">{{ $order->cena }}</h4>
<h4><a href="#">{{ $order->order_name }}</a>
</h4>
<p>See more snippets like this online store item at <a target="_blank" href="http://www.bootsnipp.com">Bootsnipp - http://bootsnipp.com</a>.</p>
</div>
<div class="ratings">
<p class="pull-right">15 reviews</p>
<p>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
</p>
</div>
<div class="btn-group center">
<a href="{{ route('product.makeOrder',['id' => $order->id]) }}" name="req" class="btn btn-warning">Order this product!</a>
</div>
<br>
</div>
</div>
@endforeach
控制器功能:
public function makeOrder(Request $request, $id){
$user = User::where('email', $request['email'])->first();
$findorder = Orders::find($id);
//$user->orders()->detach();
$user->orders()->attach(Orders::where('id', $findorder))->first();
return redirect()->back();
}
路线:
Route::get('/add-to-database/{id}',[
'uses' => 'AppController@makeOrder',
'as' => 'product.makeOrder'
]);
整个想法是如何在提交按钮后使用用户的id和产品的id更新表user_order来创建函数。
有任何帮助吗?
答案 0 :(得分:0)
您的makeOrder()
应该是:
public function makeOrder(Request $request, $id) {
$user = User::where('email', $request->get('email'))->first();
// this is to make sure that order is available in database
$order = Orders::findOrFail($id);
$user->orders()->attach($order->id);
return redirect()->back();
}