My query has a model "Token" that belongsToMany "App". The model "App" also belongsToMany "Token". Both are connected through a model "AppToken" with a belongsTo "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
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);
}
instead of whereHas() you can try with with() method. It will work for me. The example is written below.
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’);
}
Query:-
1)If the cap is your column name in the tokens table then you can use orderBy() like this.
$result = Token::with(‘app')->where('active',1)->orderBy(‘cap')->get();
Or
2)If not then use only 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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.