You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel三表关联查询咨询:获取用户相关三表数据的实现

Fetch Data from Users, UserDetails & UserDeviceDatas in 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 (replace name with any field from your users table)
  • User details: $userInformation->address (use whatever fields exist in your user_details table)
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:57:43