php - 与 Eloquent 的 3 方支点连接
问题描述
我们有可以通过 mysql 创建的自定义字段,这些字段由模块“拥有”(例如:机会模块想要一个“潜在销售”字段,用户部分想要一个性别字段(有 3 个选择选项) .
使用 Laravel 6 Eloquent,我正在尝试获取:
- 所有机会
- 和 custom_fields 其中类别 = '机会'
- 和相关的 custom_fields_values 通过枢轴。
然后将它们添加到集合中的“相关”数组中。所以我可以很容易地做到:
$opportunity->custom_field[x]->custom_field->name
$opportunity->custom_field[x]->custom_field_value[x]->value
D B:
custom_fields:
id, name, category (opportunity, client...), type (text, number, select, radio)
custom_field_custom_field_value (pivot):
custom_field_id, custom_field_value_id, parent_id (=id of the "parent" opportunity or client...), selected
custom_field_values:
id, value
我很想自己开始,但我 100% 被卡住了 - 甚至不知道从哪里开始使用 belongstomanys 等等......或者如果它完全可行......
解决方案
class CustomField extends Model
{
public function values()
{
return $this->belongsToMany(CustomFieldValue::class);
}
}
这样就可以了。
用法:
$custom_fields = CustomField::where('category', 'opportunity')->with('values')->get();
foreach ($custom_fields as $field) :
$field->values;
....
推荐阅读
- go - Go中没有方法的结构的多态性
- sql - 使用 COPY FROM 从 CSV 导入数据时转换列
- node.js - 重复的mongodb对象参数但只显示一个?最后一位数字四舍五入?
- pandas - 非数字数据框 pandas 的数据透视表
- facebook - 如何在 FB Graph API v6.0 上拉黑帖子?
- java - Eclipse Milo:如何获取方法参数的 DataType?
- reactjs - 单击按钮将数据推送到材料表
- python - 有没有办法在解包时将 splat-assign 分配为元组而不是列表?
- java - 在向量中插入一个元素会改变所有其他元素
- r - C 统计量和 AUC 不一致