【问题标题】:Why is $ids not visible inside callback of whereHas()?为什么 $ids 在 whereHas() 的回调中不可见?
【发布时间】:2020-08-26 19:04:30
【问题描述】:

我有以下代码:

$ids = $adGroupsOfUser->pluck('id');
$permittedTables = extensiontables_registry::whereHas('ad_groups', function($q){
  $q->whereIn("ad_group_id", $ids);
})->pluck('extensiontable_name')->toArray();

我收到此错误:

local.ERROR: ErrorException: Undefined variable: ids in E:\aether-backend\app\Http\Helpers\modelInteractions.php:51

为什么$ids 在 whereHas() 的回调中不可见?我该怎么做才能“把它放进去”?

【问题讨论】:

    标签: php laravel eloquent orm lumen


    【解决方案1】:

    使用use(...vars)从父作用域传递变量

    $ids = $adGroupsOfUser->pluck('id');
    $permittedTables = extensiontables_registry::whereHas('ad_groups', function($q) use($ids) {
      $q->whereIn("ad_group_id", $ids);
    })->pluck('extensiontable_name')
      ->toArray();
    

    【讨论】:

    • 谢谢,我自己发现了,现在想发帖,但是你比我快! :D
    猜你喜欢
    • 2018-12-09
    • 2011-09-29
    • 2011-07-08
    • 2016-08-13
    • 1970-01-01
    • 2015-10-02
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多