php - How do I get all of the results from a hasMany() relationship in Laravel? -
for example, have product, , have baseproduct.
in model product, i've specified following:
//in class product public function baseproduct() { return $this->belongsto("baseproduct", "baseproductid"); }
in baseproduct, i've specified following relationship:
//in class baseproduct public function products() { return $this->hasmany("product", "productid"); }
if select product, so:
$product::first()
i baseproduct doing following:
$product::first()->baseproduct()->get();
instead of getting array of result that, how model
of baseproduct, can of children of baseproduct, meaning products have foreign key relating baseproduct.
i've tried baseproduct()->all();
instead, isn't valid method.
edit:
i've created following chain of function calls - it's awful.
return baseproduct::find(product::first()->baseproduct()->getresults()['baseproductid'])->products()->getresults();
final edit:
i had made mistake in baseproduct
model. in products()
function, had specified return $this->hasmany("product", "productid");
productid
should have been baseproductid
.
after fixed that, use:
product::first()->baseproduct->products;
as sheikh heera had explained.
to children of baseproduct
may try this:
$bp = baseproduct::with('products')->get();
now, have collection of baseproduct
so, may use this:
$bp->first()->products
or second item collection
$bp->get(1)->products
also, may run loop (most in view after pass it):
// controller $bp = baseproduct::with('products')->get(); return view::make('view_name')->with('baseproduct', $bp);
in view
@foreach($baseproduct->products $product) {{ $product->field_name }} @endforeach
update: yes, may try this
$product = product::first(); $baseproduct = $product->baseproduct; // dump children/products of baseproduct dd($baseproduct->products->toarray());
you may chain like:
product::first()->baseproduct->products;
update: table structure should like:
table:baseproduct:
id(pk) | some_field | another_field
table:products:
id(pk) | baseproduct_id(fk) | another_field
according table structure, relationship should be
// baseproduct public function products() { return $this->hasmany("product"); } // product public function products() { // second parameter/baseproduct_id optional unless // have used else baseproduct_id return $this->belongsto("baseproduct", "baseproduct_id"); }
Comments
Post a Comment