简体   繁体   English

通过2关系获得结果Laravel

[英]Get results with 2 relationships Laravel

I have 3 models, let's say Product, Unit and Area. 我有3个型号,比方说产品,单位和面积。

There's a relationship between Product and Unit. 产品和单元之间存在关系。 A Unit may have a lot of Product. 一个单元可能有很多产品。

There's another relationship between Product and Area. 产品和区域之间还有另一种关系。 A Area may also have a lot of Product. 一个区域也可能有很多产品。

The point here is: given an Area, get all of its Product with the respective Unit. 这里的重点是:给定一个区域,将其所有产品相应的单位一起获得。

To get all of Product given an Area is easy: $area->products() , but I would like to do $area->products->with('unit') . 要获得一个区域的所有Product很容易: $area->products() ,但是我想做$area->products->with('unit')

Is there a way to do it? 有办法吗? Or I will have to do a foreach through the products array and querying each Unit for them? 还是我必须foreach product数组并为它们查询每个Unit?

You use nested relationships which are defined using dot notation. 您使用使用点表示法定义的嵌套关系。

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

That will eager load products and product->units with Area. 这将渴望用Area加载产品和product-> units。

Then you can loop through them using nested loops... 然后,您可以使用嵌套循环遍历它们。

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;
    }
}

Edit: Adding a where clause 编辑:添加where子句

If you need to add a where to the products, you need to separate the dot notation so you are querying for products and products.unit . 如果需要在产品上添加where ,则需要分隔点符号,以便查询productsproducts.unit

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

You should also check out the documentation which explains this more clearly than I probably can. 您还应该查看文档,它比我可能更清楚地解释了这一点。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM