【问题标题】:Laravel Get Data From Relation TableLaravel 从关系表中获取数据
【发布时间】:2021-08-06 10:44:07
【问题描述】:

我正在使用 Laravel 7.28 构建一个项目。我有三个名为的表;项目、标签和 project_tags。在 project_tags 表中有 project_ids 和 tag_ids。它看起来像这样:

我需要获取所有带有标签的项目,其次我需要获取带有特定标签的项目。那么我应该在模型中做什么?我应该使用哪个功能以及如何使用?以及如何获取数据?

我发现了 rtconner/laravel-tagging 包,但它是正确的方法吗?感谢您的帮助

【问题讨论】:

标签: mysql laravel model tags laravel-7


【解决方案1】:

您可能希望在项目和标签之间创建many to many 关系。

class Project extends Model
{
    public function tags()
    {
        return $this->belongsToMany(Tag::class, 'project_tags')->withTimestamps();
    }
}

然后:

// Get all projects with their tags.
Project::with('tags')->get();

// Get projects contain certain a certain tag.
Project::whereHas('tags', function ($query) {
    return $query->where('tag', 'some value');
})

此外,标签往往是polymorphic many to many 关系。所以如果你想长期手动处理标签,我建议这样设计。

另外,结帐spatie/laravel-tags 包。

【讨论】:

  • 当我运行它时,我得到了所有项目,但我只有 2 个带有这个标签的项目。我做错了吗?
猜你喜欢
  • 2020-07-01
  • 2018-02-14
  • 1970-01-01
  • 2020-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-03
  • 1970-01-01
相关资源
最近更新 更多