【问题标题】:Laravel 7 Query with() and using Where()Laravel 7 查询 with() 和使用 Where()
【发布时间】:2020-12-14 10:53:56
【问题描述】:

大家好,我有一个类似这样的查询

$query = Transaction::with(['customer', 'merchant', 'batch'])
->select(sprintf('%s.*', (new Transaction)->table));

我需要根据当前登录用户的 iso_id 过滤事务。

$query = Transaction::with(['customer', 'merchant', 'batch'])
->select(sprintf('%s.*', (new Transaction)->table))
->where('merchant.iso_id', '=', auth()->user()->isIso());

我需要比较的 iso_id 在商家表中

auth()->user()->isIso() 如果为 true,则返回正确的 iso_id,否则返回 false

所以我的第一次尝试是使用 where('merchant.iso_id', '=', auth()->user()->isIso())

但这会返回该列不存在,因为由于某种原因,它没有从交易模型切换到商家模型。

我不确定如何使用 with() 里面的东西作为我的 where() 的选择器

任何帮助将不胜感激!

【问题讨论】:

    标签: laravel eloquent laravel-7


    【解决方案1】:

    尝试使用whereHas添加约束:

    $query = Transaction::with(['customer', 'batch'])
                        ->whereHas('merchant', function ($q) {
                             $q->where('iso_id', auth()->user()->isIso());
                        })
                        ->select(sprintf('%s.*', (new Transaction)->table))
                        ->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 2020-01-01
      • 2021-05-05
      • 1970-01-01
      • 2018-01-03
      相关资源
      最近更新 更多