要获得BaseProduct的孩子,您可以尝试这样做:
$bp = BaseProduct::with('Products')->get();
现在,您有一个BaseProduct集合,因此,您可以使用以下内容:
$bp->first()->products
或者从集合中获取第二个项目
$bp->get(1)->products
此外,您可以运行这样的循环(最有可能在传递后的视图中):
// From the controller
$bp = BaseProduct::with('Products')->get();
return View::make('view_name')->with('baseProduct', $bp);
在视图中
@foreach($baseProduct->products as $product)
{{ $product->field_name }}
@endforeach
更新:是的,你可以试试这个
$product = Product::first();
$baseProduct = $product->BaseProduct;
// Dump all children/products of this BaseProduct
dd($baseProduct->products->toArray());
你可以链接:
Product::first()->BaseProduct->products;
更新:您的表结构应如下所示:
表:baseproduct:
id(pk) | some_field | another_field
表:产品:
id(pk) | baseproduct_id(fk) | another_field
根据这个表结构,关系应该是
// BaseProduct
public function Products()
{
return $this->hasMany("Product");
}
// Product
public function Products()
{
// second parameter/baseproduct_id is optional unless
// you have used something else than baseproduct_id
return $this->belongsTo("BaseProduct", "baseproduct_id");
}