0
votes

I have 3 database with 3 tables that tables are in relation.

  1. first table is registered users that has mobile from database1
  2. second one is user's info that has id , mobile , age and birth from database2
  3. third , history of users that has user_id , log and created_at from database3

I should select all records from first table then get id, age and birth from table2 with relation of mobile then sum of log from third table with relation of user_id.

I don't have user's id in table one

in my view file , i should show list of registered users with mobile, age, birth and sum of log.

I defined hasOne relation for table1 and table2 named as info, and hasMany relation for table2 and table3 named as logs

$users = Table1::query()->with([
        'info',
    ])->paginate(100);

and then in blade view for each user $user->info->logs()->where('created_at' ,'>=',$date)->sum('log')

Because table 2 and table 3 have many data , I need best query. This way is not appropriate because I have N+1 for getting logs

1

1 Answers

0
votes

Any particular reason why you want to have 3 different databases. With different databases few benefits of eloquent relationship methods is lost.

Assuming your relationships are defined as

  • User hasOne UserInfo
  • UserInfo hasMany Logs
$users = User::query()
    ->with([
        'info.logs' => fn($query) => $query->whereDate('created_at', '>=', $date)
    ])
    ->paginate(100);

Then in the blade you can use

$user->info->logs->sum('log');