【问题标题】:Cannot access Intermediate table in HasManyThrough relationship无法访问 HasManyThrough 关系中的中间表
【发布时间】:2020-11-24 14:06:26
【问题描述】:

我的数据库架构看起来像 this.

现在,在工匠修补模式下,当我尝试从用户模型查询详细信息表时,它会显示详细信息表的记录,但由于某种原因我无法访问案例模型,它总是在修补程序中返回 NULL。

这是我的用户模型

public function details()
{
    return $this->hasManyThrough('App\Models\Detail', 'App\Models\Cases', 'user_id', 'case_id', 'id', 'id');
}

我做错了什么?

【问题讨论】:

  • 尝试访问案例时遇到什么错误?您是否为用户模型上的案例定义了关系?
  • 它在修补模式下显示为 NULL。如上所述,我在用户模型中使用了 hasManyThrough 关系。我是否也必须分别关联 User 和 Cases 模型?
  • hasManyThrough 按照设计跳过中间表。
  • 是的,如果你想通过用户记录访问它,你需要在用户模型上定义案例关系

标签: php laravel eloquent-relationship


【解决方案1】:

如果为方便起见,您想直接从 User 模型访问详细信息,那么您可以将关系定义为 -(可能看起来有点重复,但如果可以轻松实现,则值得)


class User extends Model
{
    public function cases()
    {
        return $this->hasMany(Case::class);
    }

    public function details()
    {
        return $this->hasManyThrough(Detail::class, Case::class);
    }
}


class Case extends Model
{
    public function details()
    {
        return $this->hasMany(Detail::class);
    }

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

class Detail extends Model
{
    public function case()
    {
        return $this->belongsTo(Case::class);
    }
}

现在可以通过用户记录直接访问案例和详细信息

$user->cases;

$user->details;

【讨论】:

    【解决方案2】:

    hasManyThrough 的思想是跳过中间表。如果您需要查看案例和细节,也许您应该为其定义其他关系。

    // User model
    public function cases()
    {
        return $this->hasMany(Cases::class, 'user_id');
    }
    
    // Cases model
    public function details()
    {
        return $this->hasMany(Detail::class, 'user_id');
    }
    
    $users = User::with('cases.details')->get();
    
    foreach ($users as $user) {
        // an user
        foreach ($user->cases as case) {
            // a case
            foreach ($case->details as $detail) {
                // the details of a case
            }
        } 
    }
    

    【讨论】:

    • 感谢您对 hasManyThrough 关系的提醒。
    猜你喜欢
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 2018-07-24
    • 2014-09-22
    • 2018-10-18
    • 2023-03-09
    • 2015-10-13
    • 2020-04-16
    相关资源
    最近更新 更多