gpt4 book ai didi

Php 变量没有传递到 whereHas 函数 - Laravel Eloquent

转载 作者:可可西里 更新时间:2023-11-01 00:12:26 24 4
gpt4 key购买 nike

总结:我无法访问 whereHas 函数中的 $domain 变量(如下); Laravel 返回以下错误:

"Undefined variable: domain"

我将我的关系包括在内,因为我不确定 Eloquent 性质以及我尝试调用此查询的方式是否会导致问题。


我有一个调用模型 (Org) 的中间件

Org 模型有字段

subdomain

组织模型有

public function domains()
{
return $this->hasMany('App\Domain');
}

模型(表名域)有字段

domain, org_id

还有功能

public function org()
{
return $this->belongsTo('App\Org');
}

我可以在这个函数之前 dd($domain); 没有问题。然而,我得到了一个

"Undefined variable: domain"

对于下面 whereHas 函数中的查询参数。

为什么laravel看不到上面设置的变量?

namespace App\Http\Middleware;
use Closure;
class DomainLookup
{

protected $org;

/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$route = $request->route();
$domain = $route->parameter('domain');
$trimmed_domain = trim($domain, (config('app.domain')));

$this->org = \App\Org::where('subdomain',$trimmed_domain)
->whereHas('domains', function($q) {
$q->where('domain', $domain);
})
->get();

if ($this->org) {
return $next($request);
}

}


}

最佳答案

你需要在函数之后调用use:

$this->org = \App\Org::where('subdomain',$trimmed_domain)
->whereHas('domains', function($q) use ($domain) {
$q->where('domain', $domain);
})
->get();

关于Php 变量没有传递到 whereHas 函数 - Laravel Eloquent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48630465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com