store has many products
是关系。
如何创建新产品,保存store_id和其他产品详细信息。
代码如下。
路线
Route::resource('stores.product', 'productcontroller');
即。带产品路线的装订模型商店。
模型Store
class store extends Model
{
public function product()
{
return $this->hasMany(product::class);
}
}
create product
查看。
<form method="POST" action="/stores/{{$store->id}}/product" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
name <input type="text" name="name" />
</div>
productController@store
public function store ( store $store, Request $request )
{
$this->validate($request, [
'name' => 'required|max:255',
'detail' => 'nullable' ,
]);
$product = new product;
$product-> user_id = auth()->id();
$product-> store_id = $store->id;
$product-> name = $request->name;
$product->save();
return redirect('/stores/{{$store->id}}/product');
}
请解释路径模型绑定如何在关系中起作用。
我的创作形式的方法和行动应该是什么?
productController@store
应该在何处返回重定向?
答案 0 :(得分:0)
首先,您必须创建商店和产品之间的反向关系 像这样:
class Store extends Model
{
public function products()
{
return $this->hasMany(Product::class);
}
}
class Product extends Model
{
public function store()
{
return $this->belonsTo(Store::class);
}
}
其次,您必须将所有商店传递到创建产品页面:
public function create (){
$storList = Store::all();
return view("createproductview", compact("storList"));
}
在该页面中,您必须显示商店以选择其中一个,并从验证过程中管理您的错误:
<form method="POST" action="{ route("product.store") }}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group {{ ($errors->has('store'))?"has-error":"" }}">
<label for="store">Store</label>
<select class="form-control" name="tipoaudiencia" id="store">
<option value="">Select one option</option>
@foreach($storList as $row)
<option {{ (old("store") == $row->id ? "selected":"") }} value="{{ $row->id }}">{{ $row->name }}</option>
@endforeach
</select>
@if($errors->has('store'))<p class="help-block">{{ $errors->first('store') }}</p>@endif
</div>
<div class="form-group required {{ ($errors->has('name'))?"has-error":"" }}">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" placeholder="name" name="name" value="{{ old('name') }}" autofocus>
@if($errors->has('name'))<p class="help-block">{{ $errors->first('name') }}</p>@endif
</div>
...
</form>
并持续存储功能:
public function store ( Request $request )
{
$this->validate($request, [
'name' => 'required|max:255',
'store' => 'required'
]);
$product = new Product;
$product->name = $request->name;
$store = Store::find($request->store);
$store->products()->save($product);//this saves the product and manage the relation.
return redirect('/stores/'.$store->id.'/'.$product->id);
}
希望这能帮到你