【发布时间】:2017-01-14 05:36:47
【问题描述】:
请原谅我的新手问题,这个问题主要是由于我对 Laravel 中的多对多关系缺乏了解。
在我的网站上,用户可以上传图片
$images = new Images;
...
$images->save();
伴随着用户自己创建的标签。这些标签存储为一个数组,经过验证,然后检查标签是否存在。如果标签存在,我想要一个将新图像与该标签相关联的“tagmap”条目。如果它不存在,我希望同样的事情发生,但也创建一个新标签。
我有 3 个表,一个图像表,一个标签表和一个名为“tagmap”的数据透视表,它只有“image_id”和“tag_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');
}
}
任何帮助将不胜感激!
【问题讨论】: