Laravel Eloquent-根据父表的字段有条件地渴望加载关系

Laravel 5.8

这些是我的桌子:

# Property
-id
-type[featured,standard]
-and others fields

# Meta
-id
-property_id
-and others fields

我已经设定了雄辩的关系(hasOne) 而且,我试图实现的是仅对类型为“ featured”的属性有条件地加载元关系。

A19961217 回答:Laravel Eloquent-根据父表的字段有条件地渴望加载关系

如果您使用属性模型

运行查询
Property::with('meta')->where('type','featured')->get();

如果您代表元模型运行查询。

在此查询中,您将获得property类型具有featured的元数据

Meta::whereHas('property',function($q){
    $q->where('type','featured');
})

编辑:您的答案是正确的,但是如果我想同时获得所有特性和标准特性,并为它们添加元属性。

您想用Property来获取所有meta,然后此查询将返回Propertymeta;

Property::with('meta')->get();

您需要为此使用紧急加载

    $properties= Property::all();;
    $properties->where('type','featured')->load('meta');
    dd($properties);
本文链接:https://www.f2er.com/3167559.html

大家都在问