Laravel:每当我返回一个模型时,总是返回与它的关系 [英] Laravel: Whenever I return a model always return a relationship with it

查看:22
本文介绍了Laravel:每当我返回一个模型时,总是返回与它的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两张桌子:

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

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

Every Doctor is related to a User, but every User may not be related to a Doctor. I did it this way because I didn't want to use Single Table Inheritance and end up with a bunch of NULL fields.

有没有办法制作,像这样的东西?

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;

P.S:不知道在标题中放什么,我应该放什么来与问题更相关?

P.S: Didn't know what to put in the title, what should I put instead so it is more relevant to the question?

推荐答案

您可以使用模型上的 $with 属性指定默认的预加载关系.

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

class Doctor extends Eloquent {

    protected $with = ['user'];

    // ...
}

(该属性可能需要公开,我忘记了.如果公开,Laravel 会冲你大喊大叫.)

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

您仍然需要使用 $doctor->user->name,但关系将自动加载,无需您显式调用它.如果您真的想使用 $doctor->name 语法,您可以创建 访问器 用于这些列名称,然后将获取并传递适当的用户关系列.

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:每当我返回一个模型时,总是返回与它的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆