简体   繁体   中英

Using Laravel Eloquent's with() function along with inner join

I encountered a problem when trying to use with() function along with join:

$query = Model::query()->with([
  'relationOne',
  'relationTwo',
  ...
]);

$query->join(DB::raw("(
  select *
  from <models_table>
  where <some_condition>
) as new_model"), 'new_model.id', '=', '<models_table>.id');

$query->paginate($rpp);

After paginate($rpp) call I received all items with appropriate relations appended, but without joined table (aka new_model ). Is there a way to retrieve new_model along with relations ?

Have you tried to add select statement to emphasize the tables you want to get?

$query->join(DB::raw("(
  select *
  from <models_table>
  where <some_condition>
) as new_model"), 'new_model.id', '=', '<models_table>.id')
->select(['<models_table>.*', 'new_model.*']);

Please try the below code hope it will help you.

$query = Model::query()->with([
  'relationOne',
  'relationTwo',
  ...
])

$query = $query->join(DB::raw("(
  select *
  from <models_table>
  where <some_condition>
) as new_model"), 'new_model.id', '=', '<models_table>.id')

$query = $query->paginate($rpp);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM