And*_*zén 3 polymorphism has-and-belongs-to-many laravel laravel-4
我有3个模型,文章,建筑,人.
这些模型需要以几种方式相互引用.例如,建筑需要能够引用Person的集合,例如$ building-> architects(),$ building-> owners(),一篇文章可能引用Person的集合与$ article-> authors()和Person可能引用集合建筑物像$ person-> owned_buildings()
每个模型都应该具有类似"参考"的功能,以获得混合模型的集合.
我认为这应该是可能的,例如:
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');
}
}
Run Code Online (Sandbox Code Playgroud)
所以问题是数据透视表是什么样的?
您可以通过在混合中添加a 来定义belongsTo使用morphMany-style关系where:
public function followers() {
return $this
->belongsToMany('User', 'follows', 'followable_id', 'user_id')
->where('followable_type', '=', 'Thing');
}
Run Code Online (Sandbox Code Playgroud)
该where会只是可以肯定的口才并不失配的ID.
希望有所帮助!
| 归档时间: |
|
| 查看次数: |
4948 次 |
| 最近记录: |