【发布时间】: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);
}
【问题讨论】: