【发布时间】:2017-09-20 08:33:30
【问题描述】:
型号
public function categories()
{
return $this->belongsToMany('App\Category', 'post_categories');
}
public function posts()
{
return $this->belongsToMany('App\Post', 'post_categories');
}
控制器
public $DEFAULT_LANGUAGE = 1;
public function store(Request $request)
{
$titles = $request->PostTitle;
$post = new Post();
$post->PostTitle = $titles[$this->DEFAULT_LANGUAGE];
$post->save();
$post->categories()->attach($request->categoryID[$this->DEFAULT_LANGUAGE]);
unset($titles[$this->DEFAULT_LANGUAGE]);
foreach ($titles as $key => $title) {
$post = new Post();
$post->PostTitle = $request->PostTitle[$key];
$post->save();
$post->categories()->attach($request->categoryID[$key]);
}
return response()->json($post);
查看
<select class="form-control category-list" name="categoryID[]" multiple="multiple" data-placeholder="Pilih Kategori">
@foreach($categories as $category)
<option value="{{ $category->id }}">
{{ $category->CategoryName }}
</option>
@endforeach
</select>
如果我有两个类别并且我想选择所有类别,为什么我只得到最后一个类别?我也尝试使用 foreach,但我得到了错误偏移。 任何的想法?
我有两个选项卡窗格.. 我在选项卡 1 中存储了两个 categoryID,在选项卡 2 中存储了一个 categoryID。然后我点击提交按钮。在选项卡 1 中,标题响应两个 categoryID,但在我的数据库中,我只得到了最后一条记录
- PostTitle[1]:sadasd
- 类别ID[1]:1
- 类别ID[1]:2
- PostTitle[2]:asdasd
- 类别ID[2]:1
当我控制台时,它显示两个 CategoryID..
【问题讨论】:
-
是错字吗?
BelongsToMany应该是belongsToMany -
你可能想要使用 sync() 而不是 attach();
-
您是如何在视图中获得
$categories的?? -
@linktoahref 也一样。。我换成了belongsToMany,还是只得到最后一条记录。。
-
@Maraboc 我把 $categories = Category::all();在创建控制器
标签: php laravel model laravel-eloquent