【问题标题】:Laravel Eloquent relationship hasonethrough return an empty arrayLaravel Eloquent 关系 hasonethrough 返回一个空数组
【发布时间】:2019-07-11 12:46:18
【问题描述】:

我通过库照明/数据库使用 Eloquent,而不是 Laravel。

我有一个 users 表,一个 stripe_customer_ids 表,我在 Stripe 生成它后保存条带客户 ID,还有一个 user_stripe_subscriptions 表,我保存有关订阅的详细信息。

我需要在 user_stripe_subscriptions 表中使用用户表中的用户数据检索用户的订阅 ID。

我尝试按照 Laravel 文档更改外键和本地键选项中的许多选项,但查询仍然返回一个空数组。

这是我在 User 模型中设置的关系:

public function userStripeSubscription() {
        return $this->hasManyThrough('\App\Models\UserStripeSubscription', '\App\Models\StripeCustomerId', 'user_id', 'stripe_customer_id', 'id', 'id');
    }

在 StripeCustomerId 模型中,与 User 模型的关系通过以下方式设置:

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

并且与 UserStripeSubscription 的关系设置为:

public function userStripeSubscriptions() {
        return $this->hasOne(UserStripeSubscription::class, 'stripe_customer_id', 'stripe_customer_id');
    }

在 UserStripeSubscription 模型中存在与 StripeCustomerId 模型的关系:

public function stripeCustomerId() {
        return $this->belongsTo(StripeCustomerId::class, "stripe_customer_id", "stripe_customer_id");
    }

显然,表格已正确填充,因此我希望使用以下代码得到结果:

$user   = User::where('id', $userId)->with('userStripeSubscription')->first();

但我只得到用户的数组和一个像这样的空数组:

["relations":protected]=>
  array(1) {
    ["userStripeSubscription"]=>
    object(Illuminate\Database\Eloquent\Collection)#40 (1) {
      ["items":protected]=>
      array(0) {
      }
    }
  }

提前感谢您的帮助!

【问题讨论】:

    标签: php eloquent foreign-keys relationship


    【解决方案1】:

    第二个本地密钥不正确:

    public function userStripeSubscription()
    {
        return $this->hasManyThrough(
            '\App\Models\UserStripeSubscription', '\App\Models\StripeCustomerId',
            'user_id', 'stripe_customer_id',
            'id', 'stripe_customer_id'
        );         ^^^^^^^^^^^^^^^^^^
    }
    

    【讨论】:

    • 复制代码时出错。我已将其设置为“id”,但结果是一样的......
    • 你记录了执行的查询吗?
    • 嗯...不。如何使用 Eloquent 做到这一点?
    • 您的第一个回复是正确的!这是我的错!会话已过期,因此它给了我 NULL 因为 $userId 变量为空。非常感谢,也感谢您向我展示了调试查询的方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 2020-02-02
    • 2020-10-24
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    相关资源
    最近更新 更多