database - Laravel 将任何模型变形为用户模型
问题描述
我的任务是向用户添加加星标的项目。项目可以是(Sample、Publication、Message、atc..)。所有项目都是具有自己的表的 Eloquent 模型,如samples
, publications
,messages
和主键id
。
我想通过一张表(user_starrable)将这些模型作为加星标的项目与用户相关联。该表的结构可以类似于
id - integer
user_id - integer
model_id - integer (value like 1)
model_type - string (value like \App\Models\Sample)
我试图通过变形关系来做这几天,但没有成功。我无法在模型上编写正确的方法来完成这项工作。最后,我需要通过代码查询一个集合中的所有模型,$user->starrables()->get()
并且我希望将所有模型放在一起(样本、出版物和消息,如果存在关系)。谢谢!
楷模:
用户.php
class User
{
protected $table = 'users';
protected $hidden = [
'password', 'remember_token',
];
public function starred() { // that i cant write
return $this->morphTo();
}
}
示例.php
class Sample
{
protected $table = 'samples';
public function starrable() {
return $this->morphOne(User::class, 'starred');
}
}
发布.php
class Publication
{
protected $table = 'publications';
public function starrable() {
return $this->morphOne(User::class, 'starred');
}
}
消息.php
class Message
{
protected $table = 'messages';
public function starrable() {
return $this->morphOne(User::class, 'starred');
}
}
解决方案
推荐阅读
- angular - 检测 Angular 应用程序中缺失的增强导入
- c# - 如何从 Windows 窗体中的另一个类修改 PictureBox?C#
- javascript - 我已经从 javascript 将表格附加到 html 中,但现在我想通过传递它们的 id 从字体真棒图标调用 onclick 函数
- oauth-2.0 - oauth 2.0 - Resource owner password flow, can use windows login user credentials
- r - 在 Tidyverse 管道中使用汇总值进行归一化
- c# - wpf 列表框绑定 XElement 未更新
- android - TouchableOpacity onPress 在 Android 上不起作用
- max - 最大运费 prestashop 1.7
- phpstorm - Why is yarn not found as a package manager in PhpStorm?
- google-apps-script - appmaker 中的手风琴