[英]Save data and attach at same time in Laravel
I have a blog app that I need to add tags on post. 我有一个博客应用程序,我需要在帖子上添加标签。 I have an input field, post model, tag model and 3 tables on database:
posts
, tags
and tag_post
with ManyToMany relationship. 我有一个输入字段,帖子模型,标签模型和数据库上的3个表:
posts
, tags
和tag_post
与ManyToMany关系。
When I try to add new tag on table, it send to tag_post table and not tag table. 当我尝试在表上添加新标记时,它会发送到tag_post表而不是标记表。 I did trying change my model and controller but it worse.
我确实尝试改变我的模型和控制器,但它更糟糕。
Post Model 发布模型
<?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');
}
}
Tag Model 标签模型
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 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!');
}
Form 形成
<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>
I edit the if statement but i have this error when i save tags
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
我编辑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
Try to save your tag before attaching it to a post. 在将标签附加到帖子之前尝试保存标签。
Instead of: 代替:
...
if ($tag) {
// Do your stuff
}
do this: 做这个:
...
if ($tag->save()) {
// Do your stuff
}
By doing so, the tag is going to be saved in the tag
table in your database. 通过这样做,标记将保存在数据库的
tag
表中。 After that, in your if statement, your are going to attach the post
to that tag
you just saved. 之后,在if语句中,您将把
post
附加到刚保存的tag
。
Hope it helps! 希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.