【问题标题】:laravel eloquent complex select inside where statementlaravel 雄辩复杂的 select inside where 语句
【发布时间】:2020-07-22 13:46:37
【问题描述】:

晕,我有数据,想显示如下图

有两种模型关系,Person和Installment。

这是 Person 模型:

class Person extends Model
{
    protected $table = 'person';
    public function angsuran()
    {
        return $this->hasMany(Installment::class);
    }
}

这是分期付款模式:

class Installment extends Model
{
    protected $table = 'installment';
    public function person()
    {
        return $this->belongsTo(Person::class);
    }
}

这是我查询和显示数据的控制器

$data = Person::with('angsuran')
        ->whereHas('angsuran', function ($q) {
             $q->whereBetween('installment_date', [\DB::raw('CURDATE()'), \DB::raw('CURDATE() + INTERVAL 7 DAY')])
               ->where('installment_date', '=', function () use ($q) {
                  $q->select('installment_date')
                    ->where('status', 'UNPAID')
                    ->orderBy('installment_date', 'ASC')
                    ->first();
                });
            });
return $data->get();

它显示错误 where 子句中的未知列 person.id 请帮忙。谢谢。

【问题讨论】:

  • $q 应该在函数内 ($q) 而不是使用 ($q)
  • 我已经做了那个显示错误,例如查询不知道表名
  • 是的,您还需要指定一个表,$q->select('installment_date').. 但是从哪里开始?你可以使用 $q->from('table_name')->select(...

标签: php mysql laravel


【解决方案1】:

使用withwhereHas,即使您的子查询中有limit(1),您最终也会得到两个查询,结果将显示与person 模型相关的所有4 个分期付款。我也不认为你可以在子查询上订购,它应该在 ->get

之前

所以我已经重写了你的代码

$callback = function($query) {
    $query->whereBetween('installment_date', [today(), today()->addDays(7)])
            ->where('status', 'UNPAID')
            ->orderBy('installment_date');
    };

$data = Person::whereHas('angsuran', $callback)->with(['angsuran' => $callback])->get();

或者您可以使用查询范围。请看这个答案Merge 'with' and 'whereHas' in Laravel 5

【讨论】:

    【解决方案2】:

    正如评论所说,您需要将$q 作为闭包的参数。

    使用子查询时,告诉查询生成器它应该从哪个表查询是很有用的。

    我已经重写了您的查询。它应该实现您正在寻找的东西。此外,将 CURDATE 更改为 Carbon 对象。

    today() 返回到今天 00:00:00 的日期时间。如果您需要小时、分钟和秒,请将today() 替换为now()

    $data = Person::with('angsuran')
    ->whereHas('angsuran', function ($subquery1) {
        $subquery1->where('installment_date', function ($subquery2) {
            $subquery2->from('installment')
            ->select('created_at')
            ->where('status', 'UNPAID')
            ->whereBetween('installment_date', [today(), today()->addWeeks(1)])
            ->orderBy('installment_date')
            ->limit(1);
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2014-09-20
      • 2014-01-03
      • 2015-05-17
      • 2017-10-18
      • 1970-01-01
      • 2020-03-19
      • 1970-01-01
      • 2018-05-19
      • 2021-02-13
      相关资源
      最近更新 更多