【问题标题】:Seting up a relationship in Eloquent在 Eloquent 中建立关系
【发布时间】:2021-10-18 14:57:55
【问题描述】:

我有 3 张桌子:

  • 项目
  • 工作
  • 类别

项目有工作,工作被分配到类别。作业表包含一个项目 ID 和一个类别 ID,即作业链接到项目和类别。我的问题:

  • 如何在项目模型上设置关系以查询给定类别 ID 的项目
  • 如何在类别模型上设置关系以查询项目

diagram

【问题讨论】:

  • 您阅读了文档,然后试一试。
  • 我做到了,但我无法通过jobs表查询项目记录。你能给我一个例子还是只是一个提示?谢谢。

标签: laravel eloquent


【解决方案1】:

知道了!

查询项目模型的类别。通过这种关系,projects 可以查询他们的jobs 分配到的所有category 记录。

// In Project model class
public function categories()
{ 
    $relation = $this->hasManyThrough(
        Category::class,  // target model
        Job::class,       // intermediate model
        'project_id',     // column with project ID in jobs table
        'id',             // ID column in categories table
        'id',             // ID column in projects table
        'category_id'     // column with category ID in jobs table
    );

    // remove duplicates
    $relation->getQuery()->distinct();

    return $relation;
}

通过类别模型查询项目。通过这种关系,categories 可以查询分配给给定类别的jobs 的所有project 记录。

// In Category model class
public function projects()
{
    $relation = $this->hasManyThrough(
        Project::class,     // target model
        ProjectJob::class,  // intermadiate model
        'category_id',      // column with category ID in jobs table
        'uuid',             // ID column in projects table
        'uuid',             // ID column in categories table
        'project_id'        // column with project ID in jobs table
    );

    // remove duplicates
    $relation->getQuery()->distinct();

    return $relation;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-24
    • 2021-02-06
    • 2019-03-05
    • 2019-01-21
    • 1970-01-01
    • 2020-06-28
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多