Laravel 以雄辩的关系获取家长数据

Laravel 以雄辩的关系获取家长数据,laravel,eloquent,lumen,laravel-eloquent,Laravel,Eloquent,Lumen,Laravel Eloquent,我有这样的桌子: 主表 id titile desc 1 one one is one 2 two two is two 儿童桌 id value master_id 1 first 1 2 second 1 3 third 1 4 fourth

我有这样的桌子:

主表

    id      titile      desc
    1       one         one is one
    2       two         two is two
儿童桌

    id      value       master_id
    1       first       1
    2       second      1
    3       third       1
    4       fourth      1
因此,当我成功检索数据时,它将是一个json,如下所示:

    Master_Table {
        id:1,
        title:'one',
        desc: 'one is one',
        Child_Table: [
            {id: 1, value:"first", master_id:1},
            {id: 2, value:"second", master_id:1},
            {id: 3, value:"third", master_id:1},
            {id: 4, value:"fourth", master_id:1},
        ]
    }
    $json= PDH::find(1)->products()->where('product_highlight_id', 1)->get();
我是这样做的:

    Master_Table {
        id:1,
        title:'one',
        desc: 'one is one',
        Child_Table: [
            {id: 1, value:"first", master_id:1},
            {id: 2, value:"second", master_id:1},
            {id: 3, value:"third", master_id:1},
            {id: 4, value:"fourth", master_id:1},
        ]
    }
    $json= PDH::find(1)->products()->where('product_highlight_id', 1)->get();
但结果只有孩子

        Child_Table: [
            {id: 1, value:"first", master_id:1},
            {id: 2, value:"second", master_id:1},
            {id: 3, value:"third", master_id:1},
            {id: 4, value:"fourth", master_id:1},
        ]
我相信,这是在拉威尔雄辩可用,但我几乎找不到它。有人能给我指一下吗

提前谢谢

使用以下方法:


然后,
$pdh
将包含父对象,
$pdh->products
将是一个产品集合。

您不需要再次检查
product\u highlight\u id
,因为您已经检查以获取
主对象,并且您拥有相应的
子集合

$json = PDH::with('products')->where('id', 1)->first();

我假设PDH是您的主模型。

非常好!我只需要更改where子句。谢谢!:)
first
find
之间有什么不同?看看这里