【发布时间】:2017-09-20 16:58:16
【问题描述】:
我正在尝试使用 laravel 创建一个简单的博客。
不幸的是,我在尝试通过雄辩的多对多关系将标签附加到新帖子时迷路了。
任何帮助将不胜感激:
型号:
//post.php
public function blogTags(){
return $this->belongsToMany('BlogTag', 'blogTag_post', 'post_id', 'blogTag_id');
}
//BlogTag.php
public function posts(){
return $this->belongsToMany('Post', 'blogTag_post', 'blogTag_id', 'post_id');
}
从视图标记html($categories从get方法传入):
<h3> Tags </h3>
<select multiple class="form-control" id="tag">
@foreach ($categories as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
@endforeach
</select>
</div>
我的控制器中的存储功能
$post = new Post();
$post->post_title = Input::get('post_title');
$post->month = Input::get('month');
$post->date = Input::get('date');
$post->post_body = Input::get('post_body');
$post->picture_path = $destinationPath ."/". $filename;
$post->post_author = $author;
$post->save();
foreach (Input::get('tag') as $tagId) {
// look up the existing Tag by ID
$tag = BlogTag::find($tagId);
// save the Tag on the Post
$post->blogTags()->save($tag);
}
我想我已经在兜圈子了。
具体来说,我的问题是:
- 如何将多个值从选择输入发送到我的控制器方法?
-
$post->blogTags()->save($tag);是使用 eloquent 将数据附加到数据透视表的正确方法吗?
TIA
【问题讨论】: