I have 2 tables:

User        |   Doctor
----------  |  ----------
id          |  id
email       |  user_id
name        |  signature
last_name   |  photo
password    |  description
date_birth  |

DoctorUser相关,但每User不一定与Doctor相关.我这样做是因为我不想使用单表继承,最终得到NULL个字段.

Is there a way to make, something like this?

// Instead of
$doctor = Doctor::with('User')->find(1);
$doctor->user->name;
// This
$doctor = Doctor::find(1);
$doctor->name;

附言:我不知道该在标题中写些什么,我应该写些什么,这样它才与问题更相关?

推荐答案

You can specify default eager loaded relationships using the $with property on the model.

class Doctor extends Eloquent {

    protected $with = ['user'];

    // ...
}

(The property might need to be public, I forget. Laravel will yell at you if it does.)

You will still need to use $doctor->user->name, but the relationship will be automatically loaded without you needing to explicitly call it. If you really want to use the $doctor->name syntax, you could create Accessors for those column names, which would then fetch and pass the appropriate User relationship columns.

Laravel相关问答推荐

Laravel复选框值更新

如何解决此 Backblaze B2 S3 兼容 API 错误?

使用两个日期之间的范围获取两列之间的记录,同时搜索过滤条件

Laravel 9:AWS S3 检索要流式传输的视频

使用 Laravel 计算页面浏览量

Laravel Eloquent - 随叫随到的加密/解密数据

Laravel:如何在 laravel 查询生成器中使用派生表/子查询

即使上传了文件,Laravel Input::hasFile('image') 也会返回 false

调用未定义的函数 App\Http\Controllers\ [函数名]

Laravel 4:读取由 javascript 设置的 cookie

控制器中的 Laravel Auth 用户 ID

如何在同一行显示 Laravel artisan 命令输出?

如何在 Eloquent 上设置条件关系

Laravel - 批量分配异常错误

Laravel 随机排序

Laravel 中的单会话登录

Laravel 接口

使用哪个 Auth::check() 或 Auth::user() - Laravel 5.1?

如何在脚本文件中使用 Laravel Blade?

搜索结果分页 laravel 5.3