【问题标题】:Laravel : How to retrieve information from another table using a pivot table?Laravel:如何使用数据透视表从另一个表中检索信息?
【发布时间】:2022-01-15 19:42:07
【问题描述】:

问题是我有表单,我想获取它的所有成员。

我创建了一个 table pivot groups,它从 table forms 中检索 form_id,从 表用户。 但是当我尝试检索信息时,我得到了这个: 尝试在 bool 上读取属性“firstname”(查看:/.../resources/views/groupes/list.blade.php)

在我的模型中,我有: 表格:

public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function groupe()
    {
        return $this->belongsToMany(Groupe::class);
    }

用户:

public function forms()
    {
        return $this->hasMany(Forms::class);
    }

public function groupe()
    {
        return $this->belongsToMany(Groupe::class);
    }

list.blade.php($forms 对应于我之前在所有表单中创建过的 1 个单一表单):

@foreach($forms->user as $user)
  {{$user->firstname}}
@endforeach

【问题讨论】:

  • $forms->user 既不是集合也不是数组。它是从 Form 模型中的 belongsTo 关系获得的用户实例。这就是错误发生的原因
  • 如前所述,这是您尝试迭代的模型实例,而不是模型的集合...当您像这样迭代对象时,您将获得它的公共属性

标签: php laravel model laravel-8 laravel-blade


【解决方案1】:

Groupe 是您的数据透视表,其中包含 user_id 和 form_id。正如docs 所述,如果数据透视表未按字母顺序连接两个相关模型名称(在这种情况下应为form_user),则您需要包含表名称,即groupe

public function groupe(): BelongsToMany
{
    return $this->belongsToMany(Groupe::class, 'groupe');
}

如果你想得到Userform,那么:

public function getFormWithUser()
{
    $form = Form::with('groupe')->first();
}

*注意:但我对User 模型中的form 关系有点困惑,反之亦然,如果这个关系是Many to Many(因为有groupe 枢轴模型),它们怎么可能与每个关系其他直接?

【讨论】:

    猜你喜欢
    • 2021-02-06
    • 2020-04-06
    • 2021-01-22
    • 2015-09-02
    • 2020-01-23
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    相关资源
    最近更新 更多