laravel |查询返回所有记录的集合,即使使用find也是如此

时间:2017-05-15 13:21:24

标签: mysql laravel eloquent laravel-5.4

我正在尝试在急切加载时获取关系中的已删除记录,但我会返回所有记录而不是具有相应id的记录

以下是有问题的查询,

$collections = User::findOrFail($id->id)->with(['collection' => function ($query) {
$query->where('created_at', '>=', Carbon::today())->with(['loan' => function ($query) {
$query->withTrashed()->with(['customer' => function ($query) {
$query->withTrashed();
}]);
}]);
}])->get();

这给我一个像

的结果
Collection {#257 ▼
  #items: array:2 [▼
    0 => User {#265 ▶}
    1 => User {#266 ▶}
  ]
}

这里出了什么问题?

1 个答案:

答案 0 :(得分:0)

您应该在with之前执行findOrFail,但是这两者并不是真正兼容的事情。请改为:

$collections = User::with(['collection' => function ($query) {
    $query->where('created_at', '>=', Carbon::today())->with(['loan' => function ($query) {
            $query->withTrashed()->with(['customer' => function ($query) {
                    $query->withTrashed();
                }]);
        }]);
}])->where("id",$id->id)->firstOrFail();