To achieve an inner join using Eloquent's with method, you need to understand that with is used for eager loading relationships, not for joining tables directly. However, you can use the join method directly on the query builder to perform joins. Here's how you can modify your code to include joins:
$result = MyModel::with(['TableA' => function ($query) {
$query->with('TableB');
}])
->whereMyType($indexMyType)
->join('TableC', 'TableC.id', '=', 'TableB.table_c_id')
->join('TableD', 'TableC.id', '=', 'TableD.table_d_id')
->get();
Explanation:
-
Eager Loading with
with:- The
withmethod is used to eager load relationships. In your case,TableAis being eager loaded with its relationship toTableB.
- The
-
Joining Tables:
- Use the
joinmethod to perform SQL joins. In this example,TableCis joined withTableBon the condition thatTableC.idequalsTableB.table_c_id. - Similarly,
TableDis joined withTableCon the condition thatTableC.idequalsTableD.table_d_id.
- Use the
-
Chaining Methods:
- You can chain the
joinmethods after thewithmethod to include the necessary joins in your query.
- You can chain the
-
Fetching Results:
- Finally, use
get()to execute the query and retrieve the results.
- Finally, use
This approach allows you to combine eager loading with direct SQL joins in Eloquent. Make sure that the relationships and foreign keys are correctly defined in your models for the eager loading to work as expected.