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!

图片转代码服务由CSDN问答提供 功能建议

我是Laravel / Eloquent的新手。 我有一个关于从表中访问数据的问题。 db结构是

  1. 表1(我想加载此表)
    • 没有FK到任何其他表。
    • 表2
      • 包含表1的FK
      • 表3(当我需要表1的数据时,我有此表的PK)
        • 包含FK到表2 < / ul>



  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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);
    解决 无用
    打赏 举报

相关推荐 更多相似问题