Laravel三表关联查询咨询:获取用户相关三表数据的实现
Hey there! Let's get your query sorted to pull data from all three tables smoothly. Since you already have the relationships defined in your User model, we can build on that to create a clean, efficient method in the UserDetails model.
Step 1: Update the userDetail Method in UserDetails Model
First, we need to define the inverse relationship from UserDetails back to User (since your User model already has a hasOne link to UserDetails). Then we'll use Laravel's eager loading (with()) to fetch the related User and its associated UserDeviceData records in a single query—this avoids the annoying N+1 query problem.
Here's the updated UserDetails model code:
namespace App\Models; use Illuminate\Database\Eloquent\Model; class UserDetails extends Model { // Define inverse relationship to User public function user() { return $this->belongsTo(User::class); } // Your static method to fetch combined data public static function userDetail($userId) { // Eager load the related User and its UserDeviceData collection return self::with('user.UserDeviceData') ->where('user_id', $userId) ->first(); } }
Step 2: Use the Method in Your LoginController
Your existing call will now return all the combined data you need—no changes needed here, it just works better now:
$userInformation = UserDetails::userDetail($user->id);
Step 3: Access the Combined Data
You can now easily pull data from all three tables like this:
- User basic info:
$userInformation->user->name(replacenamewith any field from youruserstable) - User details:
$userInformation->address(use whatever fields exist in youruser_detailstable) - User device data: Loop through the collection of device records:
foreach ($userInformation->user->UserDeviceData as $device) { echo $device->device_serial; // Swap with your actual device table field name }
Alternative Approach (Starting from User Model)
If you prefer a more intuitive flow, you could also fetch everything directly from the User model:
$user = User::with(['UserDetails', 'UserDeviceData']) ->find($user->id);
Then access data as $user->UserDetails->phone for user details, and $user->UserDeviceData for the device records collection.
内容的提问来源于stack exchange,提问作者Javed

