donglang2010 2017-07-15 16:17
浏览 37
已采纳

Eloquent - 查看表1的数据,同时具有表3的PK

I am new to Laravel/Eloquent. I have a question about accessing data from a table. The db structure is

  1. Table 1 (I want to load this table)
    • No FK to any other table.
  2. Table 2
    • Contains FK to Table 1
  3. Table 3 (I have the PK for this table, when I need data for Table 1)
    • Contains FK to Table 2

I am not sure how should the Model for Table 1 look like, as I don't have any PK or FK for that table.

Many Thanks!

  • 写回答

1条回答 默认 最新

  • doumu8217 2017-07-15 16:36
    关注

    If I understood correctly, Model3 belongs to Model2 which belongs to Model1. So, do something like this to get Model1 data by PK from Model3:

    $table1Data = Model3::find($pk)->relationToModel2()->first()->relationToModel1()->first();
    

    Or by using whereHas() method:

    $table1Data = Model1::whereHas('relationToModel2', function ($q) use ($pk) {
        $q->whereHas('relationToModel3', function ($q) use($pk) {
            $q->where('id', $pk);
        });
    })->first();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog