如果我执行以下命令:
App\Assignment::with(['unit.records' => function ($q) {
$q->where('process_date', '>=', '2016-01-01')
->where('process_date', '<=', '2018-09-27')
->orderBy('process_date')
->orderBy('process_hour')
->limit(1);
}])
->whereIn('id', [9])
->get();
然后我得到以下结果:
Illuminate\Database\Eloquent\Collection {#1104
all: [
App\Assignment {#1112
id: 9,
unit_id: 6,
start_date: "2015-11-25",
end_date: "2016-01-04",
unit: App\Unit {#986
id: 6,
records: Illuminate\Database\Eloquent\Collection {#945
all: [
App\Record {#853
id: 6624,
unit_id: 6,
process_date: "2017-09-19",
process_hour: 14,
},
],
},
},
},
],
}
请注意,加载的单元具有与查询匹配的记录。
现在,如果我使用完全相同的查询,但将另一个赋值(49)添加到我的whereIn
数组:
App\Assignment::with(['unit.records' => function ($q) {
$q->where('process_date', '>=', '2016-01-01')
->where('process_date', '<=', '2018-09-27')
->orderBy('process_date')
->orderBy('process_hour')
->limit(1);
}])
->whereIn('id', [9,49])
->get();
显示了分配49的记录,但分配9的记录不再显示:
Illuminate\Database\Eloquent\Collection {#1032
all: [
App\Assignment {#1014
id: 9,
unit_id: 6,
start_date: "2015-11-25",
end_date: "2016-01-04",
unit: App\Unit {#1283
id: 6,
records: Illuminate\Database\Eloquent\Collection {#1254
all: [],
},
},
},
App\Assignment {#1061
id: 49,
unit_id: 29,
start_date: "2017-02-24",
end_date: "9999-12-31",
unit: App\Unit {#1279
id: 29,
records: Illuminate\Database\Eloquent\Collection {#1131
all: [
App\Record {#1284
id: 6062,
unit_id: 29,
process_date: "2017-03-10",
process_hour: 13,
},
],
},
},
},
],
}
与分配9的条件匹配的记录显然是存在的,但是由于某种原因,当查询发现多个分配具有与条件匹配的单位/记录时,它不会被加载。
我还用更多的赋值对其进行了测试,在每种情况下,记录只会在数组中的最后一个赋值时显示。
这是怎么回事?
发布于 2018-09-27 18:57:09
问题是你使用:
->limit(1)
这会将关系记录的数量限制为1。只需删除此行就可以了。
发布于 2018-11-01 23:35:39
在Laravel中没有对有限制的急切加载的原生支持。
我为它创建了一个包:https://github.com/staudenmeir/eloquent-eager-limit
在父模型和相关模型中使用HasEagerLimit
特征。
class Unit extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
class Record extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
然后你可以将->limit(1)
应用到你的关系中,你就会得到预期的结果。
https://stackoverflow.com/questions/52543029
复制相似问题