2017-07-06 35 views
1

在查询中的函数的变量我有这样的事情:需要在Laravel

$configurations = Configs:all(); 

foreach($configs as $config){ 

$documents = document::whereHas('user', function ($q) { 
$q->where("portal_id", $config->id),})->get() 

... 
} 

因为$config没有查询功能定义这不起作用。

如何将$config->id对象放在那里?

回答

2

的封闭封装其范围扩大变量的范围,这意味着它具有在其中它被定义或执行的范围没有访问。它是,但是,可以继承父范围(如封闭的定义)的变量与使用关键字关闭:

$documents = document::whereHas('user', function ($q) use ($config) { 
$q->where("portal_id", $config->id),})->get() 

} 
1

可以与use()

$documents = document::whereHas('user', function ($q) use($config->id) { 
    $q->where("portal_id", $config->id),})->get() 

    ... 
    } 
1

,你也可以这样写,没有必要写foreach循环:

$configurations = Configs:all(); 
$documents = Document::whereHas('user', function($q) use($configurations) { 
    $q->whereIn('portal_id', $configurations->pluck('id'));  
}); 
+0

为什么你不在闭包里面定义'$ configurations'?只是好奇 –