【问题标题】:Saving image tags to a pivot table in Laravel将图像标签保存到 Laravel 中的数据透视表
【发布时间】: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');
  } 

}

任何帮助将不胜感激!

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    如果您有正确的命名约定,Laravel 会自动执行数据透视表过程。

    在这种情况下,您有imagestags,因此您的中间表应命名为image_tag

    然后,如果您想将标签与图像相关联,您可以使用sync() 方法。如果之前有关联的标签,可以使用syncWithoutDetaching()

    $image->tags()->sync(['array', 'of', 'tag', 'ids']);
    

    如果您不想破坏现有关系,也可以使用syncWithoutDetaching() 方法:

    $image->tags()->syncWithoutDetaching(['array', 'of', 'tag', 'ids']);
    

    【讨论】:

    • 奇数。为什么使用 image_tag 而不是 images_tags ?另外,为什么 $image->tags() 而不是 $images->tags() ?我已经做了 $images = new Images;那么为什么它变成 $image 。这里的语法非常混乱。
    • @FelixMaxime Laravel 自动化了表名关系过程。它在模型之间查找单数名称。因此,在这种情况下,单数形式的图像是图像,单数形式的标签是标签。它也总是按字母顺序排列的。所以在这种情况下image_tag 是必要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 2021-08-29
    • 2019-04-07
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    相关资源
    最近更新 更多