在 eloquent 关系中获取 parents 数据

Get parents data in eloquent relation

我有 table 这样的:

Master_Table

    id      titile      desc
    1       one         one is one
    2       two         two is two

Child_Table

    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();

但结果只有 child

        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},
        ]

我确定在 Laravel Eloquent 中可以找到它,但我很难找到它。有人可以向我指出吗?

提前致谢。

使用with()方法:

$pdh = PDH::with('products')->where('product_highlight_id', 1)->find(1);

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

您不需要再次检查 product_highlight_id,因为您已经检查过 master object 并且您有相应的 child collection

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

我假设 PDH 你的主模型。