渴望加载关系表的雄辩

时间:2015-03-27 08:02:12

标签: php laravel eager-loading

如何为下表加载雄辩的热切加载。

我想得到paul->donation[{eldery,material->clothes}, {orphan,material->aircon}] 如何通过laravel雄辩的渴望加载来获得它?

以下是数据库结构和内容

Members
+----+-------------------+
| id | name              |
+----+-------------------+
|  1 | Paul              |
|  2 | John              |
|  3 | kathy             |
|  4 | Mary              |
+----+-------------------+

donation
+----+-------------------+
| id | name              |
+----+-------------------+
|  1 | eldery care       |
|  2 | orphan school     |
+----+-------------------+


donation_member pivot
+----+-----------+-----------+
| id | member_id | donate_id |
+----+-----------+-----------+
|  1 |         1 |         1 |
|  2 |         2 |         1 |
|  3 |         4 |         1 |
|  4 |         1 |         2 |
|  5 |         3 |         2 |
|  6 |         4 |         2 |
+----+-----------+-----------+

Required Material
+----+---------------+----------------+--------------+--------------+
| id | name          | donation_id    |   priority   | is_donated   |
+----+---------------+----------------+--------------+--------------+
|  1 | medicine      |       1        |       1      |     1        | 
|  2 | clothes       |       1        |       2      |     0        | 
|  3 | aircondition  |       2        |       1      |     0        |
|  4 | Desktop       |       2        |       2      |     0        | 
+----+--------------------------------+--------------+--------------+

2 个答案:

答案 0 :(得分:0)

更容易理解的是使用懒惰的急切加载。我也喜欢用它。首先获取对象或对象的集合,然后加载关系。

$members = Member::where('material.is_donated', false)->where('priority', youngest)->get();
$members->load("donation");
$members->load("material");

为此,您需要在类成员中定义Eloquent关系方法donation()和material()。

答案 1 :(得分:0)

加载嵌套关系就像平面关系一样简单,你也可以添加约束:

// Not sure what you're trying to do with the priority, I guess
// you just want the highest one?
$highestPriority = 3;

$members = Members::with([

    'donations',

    'donations.material' => function($query) use ($highestPriority) {
        $query->where('is_dontated', false);
        $query->where('priority', $highestPriority);
    }

])->get();

但是:这些约束仅适用于关系子集,而不适用于整个收集。这意味着,如果您想获得具有最高优先级材料的所有成员和捐赠,您可能需要

  • 使用已获取的集合(类型为Illuminate\Support\Collection),可能类似于$members->filter(...)
  • 使用Joins或
  • 从反向关系(Material::where(['is_donated' => true, 'priority' => $highest)])->with(['donations', 'donations.member'])->get();
  • )接近它