让父母数据具有雄辩的关系

时间:2018-01-04 15:44:22

标签: laravel eloquent lumen laravel-eloquent

我有这样的表:

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_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中可用,但我几乎找不到它。有人能指出我吗?

提前致谢。

2 个答案:

答案 0 :(得分:5)

使用with()方法:

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

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

答案 1 :(得分:2)

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

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

我认为 PDH 是您的主模型。