获得具有 2 个关系的结果 Laravel

Get results with 2 relationships Laravel

我有 3 个模型,比如说 Product、Unit 和 Area。

Product 和 Unit 之间存在关系。一个单位可能有很多产品。

Product和Area之间还有另外一种关系。一个区域也可能有很多产品。

The point here is: given an Area, get all of its Product with the respective Unit.

要获得给定区域的所有产品很容易:$area->products(),但我想做 $area->products->with('unit')

有办法吗?或者我必须通过产品数组执行 foreach 并为它们查询每个单元?

您使用了使用圆点表示法定义的嵌套关系。

$areas = Area::with('products.unit')->get();

这将急切加载产品和产品->带区域的单位。

然后您可以使用嵌套循环遍历它们...

foreach($areas as $area) {
    foreach($area->products as $product) {

        // If units are returning many
        foreach($product->unit as $unit) {

        }

        // Or if there is only one unit per product
        $unit = $product->unit;
    }
}

编辑:添加 where 子句

如果您需要在产品中添加where,您需要将点符号分开,因此您查询的是productsproducts.unit

$area = Area::with(['products' => function($q) {
    $q->where('product_field', '=', 'something');
},'products.unit'])->find($area_id);

您还应该查看文档,它比我可能更清楚地解释了这一点。

http://laravel.com/docs/5.1/eloquent-relationships#constraining-eager-loads