简体   繁体   English

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

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

My query has a model "Token" that belongsToMany "App".我的查询有一个属于ToMany“App”的model“令牌”。 The model "App" also belongsToMany "Token". model“App”也属于ToMany“Token”。 Both are connected through a model "AppToken" with a belongsTo "App/Token".两者都通过 model“AppToken”和“App/Token”连接。

I have a working query that gets me all token that have an app connected.我有一个有效的查询,可以让我获得所有连接了应用程序的令牌。 I check the token for active and i need to check if the app is active as well.我检查令牌是否处于活动状态,我需要检查应用程序是否也处于活动状态。 I'm confused about the query for that.我对此查询感到困惑。 I tried many stuff already, as an example of what i want to achieve, i wrote a not working example code so it's more clear what i mean.我已经尝试了很多东西,作为我想要实现的一个例子,我写了一个不工作的示例代码,所以我的意思更清楚了。

Current query:当前查询:

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

The results are all "active" token that have at least one "active or inactive" app connected.结果都是连接了至少一个“活动或非活动”应用程序的“活动”令牌。

But i need all "active" token that have at least one "active" app connected.但我需要所有连接了至少一个“活动”应用程序的“活动”令牌。 (not working example): (不工作的例子):

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

My models: Token.php我的模型:Token.php

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

App.php App.php

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

AppToken.php 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);
}

instead of whereHas() you can try with with() method.而不是 whereHas() 您可以尝试使用 with() 方法。 It will work for me.它会为我工作。 The example is written below.例子写在下面。

App/Token.php应用程序/令牌.php

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

App/App.php App/App.php

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

Query:-询问:-

1)If the cap is your column name in the tokens table then you can use orderBy() like this. 1)如果上限是您在令牌表中的列名,那么您可以像这样使用 orderBy() 。

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

Or或者

2)If not then use only get(). 2)如果没有,则仅使用 get()。

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

I think i found the answer to my question:)我想我找到了我的问题的答案:)

$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