我正在尝试创建一个具有多个透视表的多态关系。我有一个可以分配给客户、角色、旅行和国家/地区的需求表。这需要是一种多对多的关系,因为相同的要求可能适用于多个国家和/或旅行和/或账户等。
然后我需要一个表,列出用户的突出需求。例如:如果用户有一个特定的帐户,并且有与该帐户相关的需求,那么这些需求将被添加到用户的需求列表中。
我的一个解决方案是首先在多对多关系中使用数据透视表将需求分配给客户、角色、旅行和国家/地区。然后,使用多态关系,我将用户连接到任何与数据透视表相关的数据透视表。
但我不知道该怎么做,或者这是否可能?
这是我的桌子:
用户需求
-id
-user_id
-requireable_id
-requireable_type
账户需求
-id
-account_id
-requirement_id
角色需求
-id
-角色id
-requirement_id
行程要求
-id
-account_id
-requirement_id
国家要求
-id
-account_id
-requirement_id
Laravel 4.1现在支持多态多对多关系。
下面的例子展示了我如何实现与产品和帖子共享照片。
数据库架构
照片
id integer
filename string
alt string
光活性
id integer
photoable_id integer
photoable_type string
型号
照片模型
class Photo extends Eloquent
{
public function products(){
return $this->morphedByMany('Product', 'photoable');
}
public function posts(){
return $this->morphedByMany('Post', 'photoable');
}
}
产品型号
class Product extends Eloquent
{
public function photos(){
return $this->morphToMany('Photo', 'photoable');
}
}
后模型
class Post extends Eloquent
{
public function photos(){
return $this->morphToMany('Photo', 'photoable');
}
}
有了以上内容,我可以访问附在产品上的所有照片,如下所示:
$product = Product::find($id);
$productPhotos = $product->photos()->all();
我还可以迭代,将所有照片显示为任何模型集合。
foreach ($productPhotos as $photo)
{
// Do stuff with $photo
}
以上内容几乎可以完全复制到您的需求中。
- 创建
requirements
表 - 创建
requireable
表 - 在
Requirement
模型中,声明所有morphedByMany关系 - In Country、Trip、Role等声明morphToMany关系
nb-我在S/O中徒手键入了这个,没有代码编辑器,所以可能会有一两个打字错误,但概念保持不变。
Laravel 4中的多态关系用于单个MODEL关联,因此您无法实现使用此方法构建的内容。这是因为数据透视表并不代表模型。