首页 > 解决方案 > 与 Eloquent 的 3 方支点连接

问题描述

我们有可以通过 mysql 创建的自定义字段,这些字段由模块“拥有”(例如:机会模块想要一个“潜在销售”字段,用户部分想要一个性别字段(有 3 个选择选项) .

使用 Laravel 6 Eloquent,我正在尝试获取:

  1. 所有机会
  2. 和 custom_fields 其中类别 = '机会'
  3. 和相关的 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 等等......或者如果它完全可行......

标签: phpmysqllaraveljoineloquent

解决方案


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; 
....


推荐阅读