例如,我有一个产品,我有一个基本产品.

在产品模型中,我指定了以下内容:

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

In the BaseProduct, I've specified the following relationship:

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

If I were to select a product, like so:

$Product::first()

我可以通过以下操作获得基本产品:

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

Instead of getting the array of the result from that, how would I get the Model of the BaseProduct, so I can get all of the children of BaseProduct, meaning all Products that have a foreign key relating to this BaseProduct.

我try 了BaseProduct()->all();次,但这不是一个有效的方法.


Edit:

I've created the following chain of function calls - but it's awful.

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

最终编辑:

我在我的BaseProduct型车上犯了一个错误.在Products()函数中,我指定了return $this->hasMany("Product", "ProductId");,其中ProductId应该是BaseProductId.

在我修复它之后,我可以成功地使用:

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

正如谢赫·赫拉所解释的那样.

推荐答案

To get the children of the BaseProduct you may try this:

$bp = BaseProduct::with('Products')->get();

现在,你有BaseProduct个集合,所以,你可以使用这样的东西:

$bp->first()->products

Or get the second item from collection

$bp->get(1)->products

此外,您还可以像这样运行循环(最有可能在传递后的视图中):

// From the controller
$bp = BaseProduct::with('Products')->get();
return View::make('view_name')->with('baseProduct', $bp);

In the 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());

You may chain like:

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

Update: Your table structure should look something like:

Table:baseproduct:

id(pk) | some_field | another_field

Table:products:

id(pk) | baseproduct_id(fk) | another_field

According to this table structure, relationship should be

// 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");
}

Laravel相关问答推荐

自定义验证在表单请求上始终返回 true laravel

使用两个日期之间的范围获取两列之间的记录,同时搜索过滤条件

在 Laravel 中清除 Routes&config:cache 后未定义的常量

Laravel & Docker:无法打开流或文件/var/www/html/storage/logs/laravel.log:无法打开流:权限被拒绝

Eloquent的条件过滤器

Blade引擎:打印三重花括号

Laravel 5表单请求验证返回禁止错误

Laravel:如何通过 id 从集合中删除项目

在 laravel 如何将额外的数据传递给 mutators 和 accessors

在 Laravel 5 中扩展请求类

Laravel 监听器监听多个事件

未找到 PHP 5.4 和 Laravel 类Memcached

Laravel Blade 没有额外的空格?

如何在 AWS Elastic Beanstalk 上设置和使用 Laravel 调度?

Laravel 迁移命名约定

在 Laravel 应用程序中在哪里指定应用程序版本?

无法捕获 Carbon 抛出的异常

如何从 Laravel 中的资源中获取图像?

如何在 Laravel 5 中验证 RESTful API?

在 Laravel 中判断会话超时