我想在Laravel中 Build 多对多的多态关系 . (我是新手)
用户可以拥有许多配置文件类型配置文件类型类似于Admin,Webmaster,ProjectManager . 我为配置文件创建了一个多态关系和数据透视表 .
class User {
public function profiles(){
return Profile::where('user_id', $this->id);
}
}
class Webmaster { // and class Admin, Projectmanager
public function profiled(){
return $this->morphToMany(Profile::class, 'profileable');
}
public function saveToUser($user)
{
$profile = new Profile;
$profile->user_id = $user->id;
return $this->profiled()->save($profile);
}
}
现在我可以将模型保存到相应的用户 .
$projectManager->saveToUser($user);
$webmaster->saveToUser($user);
它会按预期保存到数据透视表中,并且关系有效 .
profiles表看起来像这样:
id
user_id
profilable_id
profilable_type
现在问题是检索我的配置文件的模型集合 . 我得到了配置文件类型,但我没有得到网站管理员和ProjectManager .
所以问题是:在这个例子中我如何获得这个模型集合?
1 回答
你的模型结构如下:
用户模型:
数据库架构:
现在,您可以检索关系:
实际上,您的 Profiles (网站管理员,管理员,项目管理员)是可以使用的 .