【问题标题】:How to check in a ::whereHas query for a certain column value? Laravel如何签入 ::whereHas 查询某个列值?拉拉维尔
【发布时间】:2021-04-16 04:03:58
【问题描述】:

我的查询有一个属于ToMany“App”的模型“Token”。模型“App”也属于ToMany“Token”。两者都通过一个模型“AppToken”和一个属于“App/Token”的模型连接起来。

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

当前查询:

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

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

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

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

我的模型: 令牌.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);
}

【问题讨论】:

    标签: php mysql sql laravel


    【解决方案1】:

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

    App/Token.php

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

    App/App.php

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

    查询:-

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

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

    或者

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

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

    【讨论】:

    • 我认为您对我的模型感到困惑。我将它们添加到我的初始帖子中。在这个查询问题中,上限无关紧要。我不能使用“with”,因为我需要过滤所有没有连接应用程序的令牌。我只希望那些在 AppToken 表中连接的令牌“whereHas”应用程序。我需要检查令牌在哪里活动以及应用程序在哪里活动。这些是 2 个不同的 col,每一个在这 2 个表中都是活动的 col。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-24
      • 2020-03-26
      • 2018-01-01
      • 2017-09-18
      • 2015-04-13
      • 2014-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多