繁体   English   中英

如何签入 a::whereHas 查询某个列值? Laravel

[英]How to check in a ::whereHas query for a certain column value? Laravel

我的查询有一个属于ToMany“App”的model“令牌”。 model“App”也属于ToMany“Token”。 两者都通过 model“AppToken”和“App/Token”连接。

我有一个有效的查询,可以让我获得所有连接了应用程序的令牌。 我检查令牌是否处于活动状态,我需要检查应用程序是否也处于活动状态。 我对此查询感到困惑。 我已经尝试了很多东西,作为我想要实现的一个例子,我写了一个不工作的示例代码,所以我的意思更清楚了。

当前查询:

$result = Token::whereHas('app')->where('active', 1)->get();

结果都是连接了至少一个“活动或非活动”应用程序的“活动”令牌。

但我需要所有连接了至少一个“活动”应用程序的“活动”令牌。 (不工作的例子):

$result = Token::whereHas('app')->where('tokens.active', 1)->where('apps.active', 1)->get();

我的模型:Token.php

public function app()
{
    return $this->belongsToMany(App::class, 'app_tokens');
}

App.php

public function tokenlist()
{
    return $this->belongsToMany(Token::class, 'app_tokens', 'app_id', 'token_id');
}

AppToken.php

protected $fillable = [
    'app_id', 'token_id',
];

/**
 * Get the app record associated with the app_id.
 */
public function app()
{
    return $this->belongsTo(App::class);
}

/**
 * Get the token record associated with the token_id.
 */
public function tokenlist()
{
    return $this->belongsTo(Token::class);
}

而不是 whereHas() 您可以尝试使用 with() 方法。 它会为我工作。 例子写在下面。

应用程序/令牌.php

public function app(){
    return $this->hasMany('App\App’)->where(‘active’,1);    
}

App/App.php

public function token(){
    return $this->hasMany('App\Token’); 
}

询问:-

1)如果上限是您在令牌表中的列名,那么您可以像这样使用 orderBy() 。

$result = Token::with(‘app')->where('active',1)->orderBy(‘cap')->get();

或者

2)如果没有,则仅使用 get()。

$result = Token::with(‘app')->where('active',1)->get();

我想我找到了我的问题的答案:)

$result = Token::whereHas('app',function ($q){
                    $q->where('active', 1);
            })->where('active', 1)->get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM