如何实现与 Eloquent 的急切加载类似的结构,但使用查询生成器?



我有3个不同的表。CCD_ 1是";主";具有主id密钥的表。

Table2Table3使用Table1id作为外键table_1_id

假设我有一些来自表1的查询:

Table1::where(...)->where(...)->get();

这给了我100个结果。

然后,我想从Table2Table3中获得ID为Table1的所有数据,但仍然有100个结果,所以当它将关系结果附加到原始模型结果时,类似于Eloquents渴望加载的结构:

Array
(
[1] => Array
(
[table2_data] => Array ( <table2_rows_array that matches id1> )
[table3_data] => Array ( <table3_rows_array that matches id1> )
)
[2] => Array
(
[table2_data] => Array ( <table2_rows_array that matches id2> )
[table3_data] => Array ( <table3_rows_array that matches id2> )
)
...
...
[100] => Array
(
[table2_data] => Array ( <table2_rows_array that matches id100> )
[table3_data] => Array ( <table3_rows_array that matches id100> )
)
)

现在我正在用whereIn进行单独的查询,但它的结构仍然不同,我需要用PHP 来操作它

要想获得加载关系,您必须:

  1. 在本例中获取基表数据Table10并创建收藏
  2. 使用table1数据id创建一个数组
  3. 获取id数组中关系列table1_id所在的相关表
  4. 在第一个table1集合的每个元素上循环,并为每个相关表添加一个属性,其中相关数据为值,其中table1_id等于当前元件id
$table1 = DB::table('table1')->select('*')->get();
$table1_ids = $table1->pluck('id')->all();
$table2 = DB::table('table1')->select('*')->whereIn('table1_id', $table1_ids)->get();
$table3 = DB::table('table1')->select('*')->whereIn('table1_id', $table1_ids)->get();
$table4 = DB::table('table1')->select('*')->whereIn('table1_id', $table1_ids)->get();
foreach($table1 as $el){
$el->table2data = $table2->where('table1_id',$el->id);
$el->table3data = $table3->where('table1_id',$el->id);
$el->table4data = $table4->where('table1_id',$el->id);
}

注意:

  • 对于foreach,我们在集合上循环,并使用collectionwhere(),因此没有进行其他查询!:D
  • 与N+1个查询不同,我们使用了一个查询来获得主模型,然后使用一个查询获得每个相关模型,在这种情况下,总共有4个查询,这与数据计数the N无关

结果

一个包含所有table1数据的单个集合,在该集合的每个元素中,与元素相关数据的每个关系(table2_data、table3_data、table4_data..)都有3个属性。

最新更新