检索多个表上的数据-laravel

vi4fp9gy  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(460)

早上好,这是我的模型:
一个基督徒可以有很多职位。一个职位可以属于许多人。邮局属于许多部门。一个部门有许多职位。
克雷蒂安

sf6xfgos

sf6xfgos1#

-部门

0..* 0..* 1..**0.. *
我怎样才能找回这样的模型?

  1. John DOE
  2. ---------------------------------------
  3. |**Postes** |**Departements**|
  4. ---------------------------------------
  5. |Pianist | Musical Group |
  6. ---------------------------------------
  7. | Secretary Curch | council |
  8. ---------------------------------------
  9. |Wedding Planer | Organizatin Comite|
sxpgvts3

sxpgvts32#

当作为属性访问有说服力的关系时,关系数据是“延迟加载的”。这意味着在您首次访问属性之前,关系数据不会被实际加载。但是,雄辩者可以在查询父模型时“急切地加载”关系。急于加载减轻了n+1查询问题。为了说明n+1查询问题,请考虑与poste相关的chretien模型:

  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. class Poste extends Model
  5. {
  6. /**
  7. * Get the chretien that wrote the poste.
  8. */
  9. public function chretien()
  10. {
  11. return $this->belongsTo('App\Chretien');
  12. }
  13. }

现在,让我们找回所有的克雷蒂安和他们的职位:

  1. $chretiens = App\Chretien::with('postes')->get();
  2. foreach ($chretiens as $chretien) {
  3. echo $chretien->postes->name;
  4. }

对于此操作,将只执行两个查询:

  1. select * from chretiens
  2. select * from postes where id in (1, 2, 3, 4, 5, ...)

嵌套急加载
要加载嵌套关系,可以使用“点”语法。例如,让我们在一个雄辩的语句中加载所有的poste和department:

  1. $chretiens = App\Chretien::with('postes.departaments')->get();
展开查看全部
lkaoscv7

lkaoscv73#

-邮政

相关问题