Laravel双重多态关系

3lxsmp7m  于 2022-12-14  发布在  其他
关注(0)|答案(1)|浏览(155)

我有三个表articleslocationscompanies。每个表的一行可以通过第四个表links与其他表的另一行链接,其中links如下所示:

  • 标识符
  • 发件人标识
  • 自类型(_T)
  • 目标标识
  • 到类型(_T)

例如,ID为1的article可以连接到ID为1的locations

  • 标识号:1
  • 发件人标识:1
  • from_type:应用程序\模型\文章
  • 收件人ID:1
  • to_type:应用程序\模型\位置

以及与公司3:

  • 编号:2
  • 发件人标识:1
  • from_type:应用程序\模型\文章
  • 收件人ID:3
  • to_type:应用程序\模型\公司

这里需要哪些laravel关系?它是某种多态的多对多关系?

rqqzpn5f

rqqzpn5f1#

实际上,这适用于链接表

class Article extends Model
{
    use HasFactory;

    public function companies()
    {
        return $this->morphToMany(Company::class, 'to', 'links', 'from_id', 'to_id', 'id', 'id', 'to');
    }

    public function locations()
    {
        return $this->morphToMany(Location::class, 'to', 'links', 'from_id', 'to_id', 'id', 'id', 'to');
    }
}

链接表

中的以下测试数据
此查询

Article::with(['companies', 'locations'])->first();

//output
App\Models\Article {#2010
     id: 1,
     title: "Et molestiae consequuntur harum provident officia neque.",
     created_at: "2020-12-07 20:18:42",
     updated_at: "2020-12-07 20:18:42",
     companies: Illuminate\Database\Eloquent\Collection {#2003
       all: [
         App\Models\Company {#2007
           id: 3,
           name: "Ledner-Schumm",
           created_at: "2020-12-07 20:18:42",
           updated_at: "2020-12-07 20:18:42",
           pivot: Illuminate\Database\Eloquent\Relations\MorphPivot {#2004
             from_id: 1,
             to_id: 3,
             to_type: "App\Models\Company",
           },
         },
       ],
     },
     locations: Illuminate\Database\Eloquent\Collection {#1999
       all: [
         App\Models\Location {#1997
           id: 2,
           name: "Maiamouth",
           created_at: "2020-12-07 20:19:08",
           updated_at: "2020-12-07 20:19:08",
           pivot: Illuminate\Database\Eloquent\Relations\MorphPivot {#2001
             from_id: 1,
             to_id: 2,
             to_type: "App\Models\Location",
           },
         },
       ],
     },
   }

而对于反关系

class Company extends Model
{
    use HasFactory;

    public function articles()
    {
        return $this->morphedByMany(Article::class, 'from', 'links', 'to_id', 'from_id', 'id', 'id');
    }
}

查询

Company::with('articles')->find(3);

//Output
App\Models\Company {#2025
     id: 3,
     name: "Ledner-Schumm",
     created_at: "2020-12-07 20:18:42",
     updated_at: "2020-12-07 20:18:42",
     articles: Illuminate\Database\Eloquent\Collection {#2026
       all: [
         App\Models\Article {#2024
           id: 1,
           title: "Et molestiae consequuntur harum provident officia neque.",
           created_at: "2020-12-07 20:18:42",
           updated_at: "2020-12-07 20:18:42",
           pivot: Illuminate\Database\Eloquent\Relations\MorphPivot {#2049
             to_id: 3,
             from_id: 1,
             from_type: "App\Models\Article",
           },
         },
       ],
     },
   }

相关问题