Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

coustas's avatar

how to make 7 join into eloquent query

hello all ,

I have this query

SELECT  scenarios.name,   scenarios.id,  applications.name FROM users INNER JOIN tokens_assign ON tokens_assign.user_id = users.id  INNER JOIN tokens ON tokens_assign.token_id = tokens.id  INNER JOIN application_tokens ON application_tokens.token_id = tokens.id  INNER JOIN applications ON applications.id = application_tokens.app_id  INNER JOIN scenario_teams ON scenario_teams.team_id = tokens.team_id  INNER JOIN scenarios ON scenarios.id = scenario_teams.scenario_id  INNER JOIN application_scenarios ON application_scenarios.scenario_id = scenarios.id AND application_scenarios.app_id = applications.id where scenario_teams.team_id=34  ORDER BY scenarios.id

how Is possible to be convert with eloquent? i mean by WITH

0 likes
7 replies
Sinnbeck's avatar

Ill get you started and you can do the rest

DB::table('users')
->select(['scenarios.name', 'scenarios.id',  'applications.name'])
->join('tokens', 'tokens_assign.token_id', 'tokens.id')
->join('applications', 'application_tokens.app_id', 'applications.id')
...etc
->where('scenario_teams.team_id', 34)
->orderBy('scenarios.id')
->get();
1 like
vincent15000's avatar

@Sinnbeck Is it possible to write two conditions in the join clause ?

INNER JOIN application_scenarios ON application_scenarios.scenario_id = scenarios.id AND application_scenarios.app_id = applications.id
1 like
rodrigo.pedra's avatar

@coustas

Would something like this help you?

$sql = /* very complex SQL query, using hard to replicate in builder features (WITH, LATERAL, etc.)  */;
$bindings = [/* query parameters to be escaped */];

$models = Model::query()->fromQuery($sql, $bindings);

Please or to participate in this conversation.