首页 > 解决方案 > Laravel billable 获取订阅未结束的记录

问题描述

我正在使用 Laravel Billable 并且我已经将它连接到不同的模型(客户端)并且一切正常。但是,我正在尝试获取订阅结束日期为空的模型上的所有记录。我正在做以下事情;

$collection = Model::where('client.subscriptions', function ($q) {
    $q->where('ends_at', NULL);
})->get();

我收到以下错误:

未定义的表:7 错误:缺少表“client”的 FROM 子句条目 LINE 1:select * from “table” where “client”.“subscriptions” =... ^(SQL:select * from “table” where “client "."subscriptions" = (选择 * 其中 "ends_at" 为空))

更新

代码更新

   $jobs = \App\Models\Job::with(['client' => function($query) {
    $query->whereHas('subscriptions', function ($query){
        $query->where('ends_at', NULL);
    });
}])->get();

示例数据库

(model) Job (db:name = 'jobs')

id | client_id | name

(model) Client (db:name = 'clients')

id | name 

(model) Subscription (db:name = 'subscriptions')

id | client_id | stripe_plan | trial_ends_at | ends_at 

客户模型

/**
 * Get all of the subscriptions for the Stripe model.
 *
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function subscriptions()
{
   // foreign key is client_id
    return $this->hasMany(Subscription::class, $this->getForeignKey())->orderBy('created_at', 'desc');
}

工作模式

public function client()
{
    return $this->belongsTo(Client::class);
}

现在使用这个查询;

 $jobs = \App\Models\Job::with(['client' => function($query) {
        $query->whereHas('subscriptions', function ($query){
            $query->where('ends_at', NULL);
        });
    }])->get();

我仍然得到订阅 end_at 不为空的记录。任何想法我做错了什么?

标签: laraveleloquentlaravel-cashier

解决方案


正确的查询是;

$jobs = Job::whereHas('client', function($query) {
    $query->whereHas('subscriptions', function ($query) {
        $query->where('ends_at', NULL);
    });
})->get();

推荐阅读