渴望加载条件是Laravel中的count()

时间:2015-02-26 10:39:33

标签: mysql laravel eager-loading

我正在尝试从表A中获取一些数据,其中表B中的结果使用了预先加载并排除了Laravel中表B中没有结果的数据。但我似乎无法得到我想要的东西。

以下是我正在使用的表格:

 * table_a                    * table_b
+---------+                  +------------+
+ id      +                  + id         +
+ user_id +                  + table_a_id +
+ colA    +                  + colA       +
+ colB    +                  + colB       +
+---------+                  +------------+

我想要的结果是:

data: [
    {
       id:       1,
       user_id:  1,
       colA:     "Some text here",
       colB:     "Other text here",
       table_b:  [
           {
               id:          2,
               table_a_id:  1,
               colA:        "some text here",
               colB:        "other text here"
           }
       ]
    },
    {
       id:       2,
       user_id:  1,
       colA:     "Some text here",
       colB:     "Other text here",
       table_b:  [
           {
               id:          5,
               table_a_id:  1,
               colA:        "some text here",
               colB:        "other text here"
           },
           {
               id:          6,
               table_a_id:  1,
               colA:        "some text here",
               colB:        "other text here"
           }
       ]
    }
]

但我得到这样的东西:

data: [
    {
       id:       1,
       user_id:  1,
       colA:     "Some text here",
       colB:     "Other text here",
       table_b:  [
           {
               id:          2,
               table_a_id:  1,
               colA:        "some text here",
               colB:        "other text here"
           }
       ]
    },
    {
       id:       2,
       user_id:  1,
       colA:     "Some text here",
       colB:     "Other text here",
       table_b:  [
           {
               id:          5,
               table_a_id:  1,
               colA:        "some text here",
               colB:        "other text here"
           },
           {
               id:          6,
               table_a_id:  1,
               colA:        "some text here",
               colB:        "other text here"
           }
       ]
    },
    {
       id:       3,
       user_id:  1,
       colA:     "Some text here",
       colB:     "Other text here",
       table_b:  null
    },
    {
       id:       4,
       user_id:  1,
       colA:     "Some text here",
       colB:     "Other text here",
       table_b:  null
    }
]

我试过了:

$user->table_a->withTableB()->where('table_b', '<>', 'null')->get(); //this doesn't work obviously

我不知道该怎么做。有帮助吗?感谢。

0 个答案:

没有答案