Laravel - 用急切加载和左连接查询 - >子对象为空

时间:2014-10-03 13:21:03

标签: mysql laravel left-join eloquent eager-loading

我有四张桌子:

    1. objects           2. objectdates       3. objectphotos        4. imagefiles
+------------------+  +------------------+  +------------------+  +------------------+
| columns          |  | columns          |  | columns          |  | columns          |
+------------------+  +------------------+  +------------------+  +------------------+
| id               |  | id               |  | id               |  | id               |
| title            |  | object_id        |  | object_id        |  |                  |
|                  |  |                  |  | imagefile_id     |  |                  |
+------------------+  +------------------+  +------------------+  +------------------+

我正在使用的查询:

$objects = Object::with(array(
    'objectdate' => function($query){
        $query->select('id', 'id AS objectdate_id', 'object_id');
    }
))
->select(
    'objects.id', 'objects.id AS object_id', 'objects.title',
    'objectphotos.id AS objectphoto_id',
    'imagefiles.id', 'imagefiles.id AS imagefile_id'
)
->leftJoin('objectphotos', 'objects.id', '=', 'objectphotos.object_id')
->leftJoin('imagefiles', 'imagefiles.id', '=', 'objectphotos.imagefile_id')
->groupBy('objects.id')->get();

MySQL输出结果:

select `objects`.`id`, `objects`.`id` as `object_id`, `objects`.`title`, 
`objectphotos`.`id` as `objectphoto_id`, `imagefiles`.`id`, 
`imagefiles`.`id` as `imagefile_id` from `objects` 
left join `objectphotos` on `objects`.`id` = `objectphotos`.`object_id` 
left join `imagefiles` on `imagefiles`.`id` = `objectphotos`.`imagefile_id` 
where `objects`.`deleted_at` is null group by `objects`.`id`


select `id`, `id` as `objectdate_id`, `object_id` from `objectdates` where `objectdates`.`object_id` 
in ('29', '36', '46', '57', '71', '91', '107', '115', '129', '141', '152', '154') order by
`objectdates`.`date` asc, `objectdates`.`timeofday` asc

关系:

  • 对象 - >的hasMany(' Objectdate&#39)
  • 对象 - >的hasMany(' objectphoto&#39)
  • Objectphoto->属于关联('镜像文件&#39)
  • (Imagefile不属于Objectphoto因为包含不是Objectphoto的图像)

我的问题:

当我使用上面的查询时,我的objectdate对象为空:

["objectdate"]=>
    object(Illuminate\Database\Eloquent\Collection)#1018 (1) {
      ["items":protected]=>
      array(0) {
      }
    }

当我删除' imagefiles'从查询中,一切都按预期工作,我得到对象objectdate中的所有日期:

$objects = Object::with(array(
    'objectdate' => function($query){
        $query->select('id', 'id AS objectdate_id', 'object_id');
    }
))
->select(
    'objects.id', 'objects.id AS object_id', 'objects.title',
    'objectphotos.id AS objectphoto_id'
)
->leftJoin('objectphotos', 'objects.id', '=', 'objectphotos.object_id')
->groupBy('objects.id')->get();

问题是这个问题特定于对象objectdates。我有另一个名为users的表,该对象在急切加载时与图像文件完美配合...

为什么我的对象在第一种情况下是空的? 我想保留1个查询,因为laravel输出是完美的

如果无法保留一个查询,如何在主对象中添加对象日期?因为我使用objectdates对结果进行排序。

感谢所有帮助。

谢谢!

0 个答案:

没有答案