Eloquent with(),select()和where()选择

时间:2015-11-07 05:29:44

标签: laravel laravel-5 eloquent

这是我从2个不同的表中获取数据的查询。

$variant = Variant::with(['v_detail' => function($q){
            $q->select('variant_dtl_name');
        }])->where('product_id','=',$productId)->get();

有输出,但v_detail返回空列表

结果:

created_at: "2015-11-07 12:37:26"
id: 1
product_id: 30
updated_at: "2015-11-07 12:37:26"
v_detail: []
variant_name: "Pricing"

但是有了这些疑问:

$variant = Variant::with('v_detail')->where('product_id','=',$productId)->get();

结果是:

created_at: "2015-11-07 12:37:26"
id: 1
product_id: 30
updated_at: "2015-11-07 12:37:26"
v_detail: [{id: 1, variant_id: 1, variant_dtl_name: "Adult", variant_dtl_price: 25,…},…]
0: {id: 1, variant_id: 1, variant_dtl_name: "Adult", variant_dtl_price: 25,…}
1: {id: 2, variant_id: 1, variant_dtl_name: "Senior", variant_dtl_price: 15,…}
2: {id: 3, variant_id: 1, variant_dtl_name: "Children", variant_dtl_price: 8,…}
variant_name: "Pricing"

现在,在有效的查询上,如何获取特定的列名。谢谢!

1 个答案:

答案 0 :(得分:0)

你有这个:

$variant = Variant::with(['v_detail' => function($q)
{
    // Either add the related foreign key or select all
    $q->select('related_foreign_key', 'variant_dtl_name');

}])->where('product_id','=',$productId)->get();

由于您只选择variant_dtl_name的单个字段,因此无法找到相关模型,因为需要使用关系构建器外键。因此,您还必须选择该外键。请注意子查询中的related_foreign_key,因此请使用正确的variant_id,但可能不确定,因为您没有提及任何相关内容。