【问题标题】:3 party pivot connection with Eloquent与 Eloquent 的 3 方支点连接
【发布时间】:2020-03-31 22:15:41
【问题描述】:

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

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

  1. 所有机会
  2. 和 custom_fields where category = 'opportunity'
  3. 和相关的 custom_fields_values 通过数据透视。

然后将它们添加到集合中的“相关”数组中。所以我可以轻松做到:

$opportunity->custom_field[x]->custom_field->name
$opportunity->custom_field[x]->custom_field_value[x]->value

数据库:

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 等等......或者它是否完全可行......

【问题讨论】:

    标签: php mysql laravel join eloquent


    【解决方案1】:
    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; 
    ....
    
    

    【讨论】:

    • 谢谢,但这将获取所有机会的所有值。我只想获取该机会的分配值(opportunity_id 由枢轴定义)此外,它将同时获取大约 1000 个机会 - 所以不想在每个机会上都“foreach”..跨度>
    猜你喜欢
    • 2022-01-23
    • 2015-01-07
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多