我有一个博客应用,我需要在帖子上添加标签。我有一个输入字段,帖子模型,标签模型和3个数据库表格:posts
,tags
和tag_post
与ManyToMany关系。
当我尝试在表格上添加新标签时,它会发送到tag_post表而不是标签表。我确实尝试过改变我的模型和控制器,但情况更糟。
发布模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $filliable = ['PostTitle', 'post', 'slug'];
public function categories()
{
return $this->BelongsToMany('App\Categories', 'category_post');
}
public function tags()
{
return $this->BelongsToMany('App\Tag', 'tag_post');
}
}
标记模型
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
protected $filliable = ['tag'];
public function posts()
{
return $this->BelongsToMany('App\Post', 'tags_post');
}
}
PostController中
public function store(Request $request)
{
$post = new Post;
$post->user_id = auth::id();
$post->PostTitle = $request->PostTitle;
$post->post = $request->post;
$post->slug = $request->slug;
$post->status = '1';
$post->save();
$post->categories()->attach($request->categories);
$tags = new Tag;
foreach($tags as $tag){
$tags->tag = $request->tags;
if($tags->save()){
$post->tags()->attach($request->tags);
}
}
return redirect('blog')->with('messageSuccess', '¡Tu entrada se ha creado Exitosamente!');
}
表格
<div class="post-panel-3">
<div class="form-group">
<label for="postTags">Etiquetas: </label>
<input type="text" name="tags[]" value=" " class="form-control" placeholder="Etiquetas" id="tagBox">
</div>
我编辑if语句但是当我保存标签
时出现此错误Type error: Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given, called in C:\laragon\www\asiviajo-app\vendor\laravel\framework\src\Illuminate\Database\Query\Grammars\Grammar.php on line 665
答案 0 :(得分:0)
尝试在将标签贴在帖子上之前保存标签。
而不是:
...
if ($tag) {
// Do your stuff
}
这样做:
...
if ($tag->save()) {
// Do your stuff
}
通过这样做,标记将保存在数据库的tag
表中。之后,在if语句中,您将post
附加到刚刚保存的tag
。
希望它有所帮助!