【问题标题】:Laravel 8 hasManyThrough not returning dataLaravel 8 hasManyThrough 不返回数据
【发布时间】:2021-04-14 15:00:50
【问题描述】:

我有 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();

【问题讨论】:

  • 为什么apps 表有app_id 列?
  • 不幸的是我不管理数据库表。 app_id 是为应用创建的单独 ID。类似“aa111”的东西。版本中的 app_id 引用它而不是主递增键。这就是我使用 hasManyThrough 指定新键的原因。

标签: laravel pivot has-many-through has-many


【解决方案1】:

我想通了,现在看到了。

我改变了这个:

$userVersions = $user->version();

到这里:

$userVersions = $user->version;

【讨论】:

    猜你喜欢
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2023-02-24
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    相关资源
    最近更新 更多