Laravel:每当我返回模型时,总会返回与之关系

Mat*_*s17 9 model laravel eloquent laravel-4

我有2张桌子:

User        |   Doctor
----------  |  ----------
id          |  id
email       |  user_id
name        |  signature
last_name   |  photo
password    |  description
date_birth  |
Run Code Online (Sandbox Code Playgroud)

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

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

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

PS:不知道在标题中放什么,我应该把它放在哪里以便它与问题更相关?

Ake*_*rts 22

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

class Doctor extends Eloquent {

    protected $with = ['user'];

    // ...
}
Run Code Online (Sandbox Code Playgroud)

(该遗产可能需要公开,我忘了.如果确实如此,Laravel会对你大喊大叫.)

您仍然需要使用$doctor->user->name,但关系将自动加载,您无需显式调用它.如果您确实想要使用该$doctor->name语法,可以为这些列名创建Accessors,然后获取并传递相应的User relationship列.


Mat*_*s17 11

我最终使用了Accessors,$appends它按预期工作.它甚至出现在文档Appends + Accessors(最后)中.感谢Cyrode,他向我展示了Accessors(他们不知道他们已经完成了).

我可能不会使用$appends数组,但是如果你在JSON中返回模型,则需要它.

正如Jarek Tkaczyk deczo建议的那样,with当你使用这种方法时应该使用属性,否则每当你加载多个Doctor模型并调用任何User相关的东西时,你最终会得到一个db查询(每个Doctor实例) - > n + 1个问题

医生课最终看起来像这样:

<?php

class Doctor extends Eloquent {

    protected $table = 'doctors';

    protected $with = ['user'];

    protected $appends = ['first_name','last_name','email','date_of_birth'];

    protected $hidden = ['signature','user'];

    public function user(){

        return $this->belongsTo('User');

    }

    public function getFirstNameAttribute() {

        return $this->user->first_name;

    }

    public function getLastNameAttribute() {

        return $this->user->last_name;

    }

  public function getEmailAttribute() {

      return $this->user->email;

  }

}
Run Code Online (Sandbox Code Playgroud)

我不得不把它放在阵列user里面,$hidden否则每当我退役时它都会出现Doctor(除了我只需要一些东西User,而不是一切)

  • 当你使用这种方法时,你应该使用`with`属性,否则每当你加载多个`Doctor`模型并调用任何与'User`相关的东西时,你最终会得到一个db查询(每个Doctor实例) - > n + 1问题 (2认同)