请原谅我的新问题,这个问题主要是由于我顽固地不理解许多对许多关系在拉维尔。
在我的网站上,用户可以上传图片
$images = new Images;
...
$images->save();
伴随着用户自己创建的标签。这些标签以数组的形式存储,验证,然后检查标签是否存在。如果标签存在,我希望在“TAGMAP”上输入一个条目,它将新图像与该标签关联。如果它不存在,我希望同样的事情发生,但也有一个新的标签被创建。
我有3个表,一个图像表,一个标记表,和一个名为“tagmap”的透视表,它只有列“image\u id”和“tag\u id”。
所以在保存图像之后:
$tags = new Tag;
foreach ($request->tags as $tags ) {
if(preg_match('/^[a-zA-Z]+[a-zA-Z0-9._]+$/', $tags)) {
if (strlen($tags) < 21) {
if (Tag::where('tagname', $tags)->count() > 0) {
//store tag_id and image_id association on 'tagmap' table, no need to create new tag because tag exists
} else {
//create new tag on the 'tags' table
//store tag_id and image_id association on 'tagmap' table
}
} else {
return redirect()->back()->with('info', 'Tags may only contain 20 characters.');
}
} else {
return redirect()->back()->with('info', 'Tags may only contain letters and numbers, and must start with letters.');
}
}
$tags->save();
评论部分是我遇到麻烦的地方。
这是我的标签型号:
class Tag extends Model {
protected $table = 'tags';
protected $fillable = [
'tagname',
];
public function Images() {
return $this->belongsToMany('CommendMe\Models\Images');
}
}
在我的图像模型中我有:
class Images extends Model {
protected $table = 'images';
public function tags() {
return $this->belongsToMany('CommendMe\Models\Tag');
}
}
任何帮助都将不胜感激!
最佳答案
如果有正确的命名约定,Laravel会自动执行透视表进程。
在这种情况下,您有images
和tags
,因此您的中间表应该命名为image_tag
。
然后,如果要将标记与图像关联,可以使用sync()
方法。如果以前关联过标记,则可以使用syncWithoutDetaching()
。
$image->tags()->sync(['array', 'of', 'tag', 'ids']);
或者,如果不想破坏现有关系,可以使用
syncWithoutDetaching()
方法:$image->tags()->syncWithoutDetaching(['array', 'of', 'tag', 'ids']);