【问题标题】:Eloquent relationship with 3 tables与3张桌子的雄辩关系
【发布时间】:2017-08-28 12:05:53
【问题描述】:

我是 Stack Overflow 和 Laravel 的新手。

我尝试在 Laravel 中开发一个变量配置文件系统,我得到了 3 个表('User'、'User_Fields'、'Fields')。

Fields 表的结构如下:

user_fields 表的结构如下:

User 表是 Laravel 5 附带的标准表

现在我想从user_fields 获取所有字段,具体取决于选择或登录的user。如果user_field 不存在,模型应该返回null 或为user_field.

我尝试了很多带有雄辩的“解决方案”,例如(hasManyThroughbelongsToMany),但我没有得到我想要的结果。

有没有关系方法的解决方案?

感谢您的帮助,抱歉我的英语不好:/

【问题讨论】:

  • 欢迎来到 SO ,你尝试了什么?
  • 我有 fields 表(在此表中声明了所有配置文件字段)和 user_fields 表(此表包含值并与 user_id 和 field_id 关联)现在我尝试检索所有配置文件fields 表中的字段具有 user_fields 表中的值,但如果相关的 user_field 不存在,则应返回 null。你知道我的意思吗?

标签: laravel eloquent relationship


【解决方案1】:

您应该使用belongsToMany()->withPivot()retrieve the intermediate table columns。您的 user_fields 是您的数据透视表,因此您的用户模型应该有:

class User extends Model
{
    public function fields()
    {
        return $this->belongsToMany(Field::class, 'user_fields')->withPivot('value');
    }
}

然后您可以通过以下方式访问用户的值:

$user = User::find($id);
foreach($user->fields as $field) {
    $field->pivot->value;
} 

【讨论】:

  • 例如,我的 fields_table 中有以下字段:名字、姓氏、地址、邮政编码、城市和国家/地区,但在我的 user_fields 表中只存在 firstname->john 和 lastname->doe。此时你的解决方案工作正常,但我想检索其余的fields_table,如地址、邮政编码等。这对user_fields没有任何价值..非常感谢你的帮助:)
猜你喜欢
  • 1970-01-01
  • 2017-04-14
  • 2019-10-18
  • 2018-12-09
  • 1970-01-01
  • 2017-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多