首页 > 解决方案 > Laravel 8 hasManyThrough 不返回数据

问题描述

我有 3 张表都是 Eloquent 模型。我正在尝试使用 hasManyThrough 或枢轴等来获取从原始表到最后一个表的关系。我现在有一个 hasManyThrough 设置,但我没有得到任何结果。就内置查询而言,来自 dd() 的查询看起来是正确的,但我没有看到任何数据。没有抛出错误。

表和 ID:

users:
id

apps:
id
user_id
app_id

appversions:
id
app_id
user_id

一个用户可以拥有许多应用程序。一个应用程序可以有多个版本。我想从他们拥有的所有应用程序中获取特定用户的所有版本。唯一的区别是版本表称为“appversions”,模型称为版本。

我在版本模型上设置表名。

class Version extends Model
{
    use HasFactory;

    protected $table = 'appversions';
}

在我的用户模型上,我正在尝试这个 hasManyThrough

public function versions()
    {
        return $this->hasManyThrough(
            'App\Models\Version', 
            'App\Models\App',
            'user_id',
            'app_id',
            'id',
            'app_id'
        );

    }

然后像这样从我的控制器调用它:

$userVersions = $user->version();

标签: laravelpivothas-many-throughhas-many

解决方案


我想通了,现在看到了。

我改变了这个:

$userVersions = $user->version();

对此:

$userVersions = $user->version;

推荐阅读