How to get all the results from a hasMany () relation in Laravel?

For example, I have a Product, and I have BaseProduct.

In the model for the product, I indicated the following:

//In class Product
public function BaseProduct()
{
    return $this->belongsTo("BaseProduct", "BaseProductId");
}

In BaseProduct, I indicated the following relationship:

//In class BaseProduct
public function Products()
{
    return $this->hasMany("Product", "ProductId");
}

If I wanted to select a product, for example:

$Product::first()

I can get BaseProduct by doing the following:

$Product::first()->BaseProduct()->get();

Instead of getting an array of the result from this, how can I get Modelfor BaseProduct, so that I can get all the children of BaseProduct, which means all products that have a foreign key related to this BaseProduct.

I tried BaseProduct()->all();instead, but this is not a valid method.


Edit:

I created the following chain of function calls - but this is terrible.

return BaseProduct::find(Product::first()->BaseProduct()->getResults()['BaseProductId'])->Products()->getResults();

Final editing:

BaseProduct. Products() return $this->hasMany("Product", "ProductId");, ProductId BaseProductId.

, , :

Product::first()->BaseProduct->products;

.

+4
1

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

View

@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");
}
+9

Source: https://habr.com/ru/post/1525523/


All Articles