如何在PHP中以一对一关系从两个表中检索数据组合?

时间:2018-08-28 10:06:25

标签: php laravel

我有两个模型,分别是UserPatient。 “患者”表中的外键为user_id

用户

class User extends Authenticatable
{
    public function patient()
    {
       return $this->hasOne(Patient::class);
    }
}

患者

class Patient extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

当我运行此脚本时,它不会检索两个表数据

$patient_user = User::find($user->id)->patient;

结果

{
    "success": {
        "id": 1,
        "user_id": 1,
        "ic": null,
        "gender": null,
        "age": null,
        "height": null,
        "weight": null,
        "allergy": null,
        "created_at": null,
        "updated_at": null
    }
}

预期结果

{
    "success": {
        "name": "Mohammad",
        "email": "mohammadnrdn@gmail.com",
        "role": 1,
        "phone_number": null,
        "country_code": null,
        "authy_id": null,
        "verified": "0",
        "ic": null,
        "gender": null,
        "age": null,
        "height": null,
        "weight": null,
        "allergy": null,
        "created_at": "2018-08-28 07:42:16",
        "updated_at": "2018-08-28 07:42:16"
    }
}

结构

CREATE TABLE `users` (
  `id` int(10) UNSIGNED NOT NULL,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `role` int(11) NOT NULL DEFAULT '1',
  `phone_number` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `country_code` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `authy_id` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `verified` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT '0',
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `patients` (
  `id` int(10) UNSIGNED NOT NULL,
  `user_id` int(11) UNSIGNED NOT NULL,
  `ic` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `gender` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `height` decimal(8,2) DEFAULT NULL,
  `weight` decimal(8,2) DEFAULT NULL,
  `allergy` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

如何实现?

1 个答案:

答案 0 :(得分:3)

在Laravel中,有Lazy eager-loading个模型,这意味着可以在检索模型后加载模型的相关模型。因此,在您的情况下,您可以为患者加载:

User::find($user->id)->load('patient')

否则,您可以constrain eager-load关系,然后再获取模型:

User::with('patient')->find($user->id)