gpt4 book ai didi

laravel - Laravel 中与数据透视表的多态关系?

转载 作者:行者123 更新时间:2023-12-02 14:32:18 24 4
gpt4 key购买 nike

我有 3 个模型,文章、建筑、人物。

  1. 这些模型需要通过多种方式相互引用。例如,建筑物需要能够引用 Person 的集合,例如 $building->architects()、$building->owners(),一篇文章可能会通过 $article->authors() 引用 Person 的集合,而 Person 可能会引用集合类似 $person->owned_buildings() 的 Building

  2. 每个模型都应该有一个像“references”这样的函数来获取混合模型的集合。

我认为这应该可以通过以下方式实现:

class Article extends Eloquent {
public function referenceable()
{
return $this->morphTo();
}

public function authors()
{
return $this->morphMany('Person', 'referenceable');
}
}

class Building extends Eloquent {
public function referenceable()
{
return $this->morphTo();
}

public function architects()
{
return $this->morphMany('Person', 'referenceable');
}
}

class Person extends Eloquent {
public function referenceable()
{
return $this->morphTo();
}

public function owned_buildings()
{
return $this->morphMany('Building', 'referenceable');
}
}

所以问题是数据透视表会是什么样子?

最佳答案

您可以通过添加 where 来使用 morphMany-style 关系定义 belongsTo:

  public function followers() {
return $this
->belongsToMany('User', 'follows', 'followable_id', 'user_id')
->where('followable_type', '=', 'Thing');
}

where 只是确保 Eloquent 不会不匹配 ID。

希望有帮助!

关于laravel - Laravel 中与数据透视表的多态关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16102144/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com