为啥 $ids 在 whereHas() 的回调中不可见?

Posted

技术标签:

【中文标题】为啥 $ids 在 whereHas() 的回调中不可见?【英文标题】: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() 的回调中不可见?我该怎么做才能“把它放进去”?

【问题讨论】:

【参考方案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

以上是关于为啥 $ids 在 whereHas() 的回调中不可见?的主要内容,如果未能解决你的问题,请参考以下文章

在 Laravel 5 中合并 'with' 和 'whereHas'

Laravel 多个 whereHas 关系标准

Sequelize 中的 WhereHas 方法

Laravel Eloquent 在 whereHas() 上进行选择

查询: 在邮递员的 whereHas 处返回,但表中有数据。拉拉维尔

Laravel - 搜索关系,包括 whereHas 中的 null