【发布时间】:2020-04-02 17:00:08
【问题描述】:
我想要实现的目标: 用户可以将多个超市分配给一个产品,超市可以分配给多个产品。注册产品时,我希望用户能够从数据库中填充的复选框中进行选择。
产品.php
class Product extends Model
{
//
protected $fillable = [
'name',
'summary',
'category_id',
'author_id',
'supermarket_id',
'gf_rank_id',
'average_price',
'photo_id',
'online_store_path',
'ingredients',
];
public function supermarket() {
return $this->belongsToMany('App\Supermarket');
}
}
Supermarket.php
class Supermarket extends Model
{
protected $fillable = [
'name',
'url',
];
public function products() {
return $this->belongsToMany('App\Products');
}
}
ProductsController.php
public function create()
{
$categories = Category::pluck('name', 'id')->all();
$supermarkets = Supermarket::pluck('name', 'id')->all();
return view('admin.products.create', compact(['categories', 'supermarkets']));
}
create.blade.php
@foreach ($supermarkets as $supermarket)
<div class="col-sm-3">
{!! Form::checkbox('supermarket_id[]', $supermarket->id) !!}
{!! Form::label('supermarkets', $supermarket) !!}
</div>
@endforeach
【问题讨论】:
-
$supermarkets是一个关联数组,以 'id' 为键,值为 'name';它不包含对象......它是一个字符串数组 -
@lagbox 那么在创建 Product 对象时我将如何保存该复选框的 id 呢?
标签: laravel checkbox laravelcollective