繁体   English   中英

数据透视表关系 Laravel

[英]pivot table relationship Laravel

我有以下关系:

  1. RAB 有很多产品。
  2. 产品属于多RAB

但是这个产品也有很多属于一个RAB本身。 它看起来像这样。

桌子

在 RAB 模型中:

  public function products()
    {
        return $this->belongsToMany('App\ModelKeuangan\ProductsModel', 'rab_products', 'rab_id', 'products_id');
    }

产品型号:

public function rab()
    {
        return $this->belongsToMany('App\ModelUnitKerja\Perencanaan\RabModel', 'rab_products', 'products_id', 'rab_id');
    }

rab_products是我的中间/连接表。

当我为 RAB 同步产品数据时,它工作得很好。 但我不知道如何制作雄辩的模型来将货币数据同步到 rab 和产品。

我也需要为货币制作模型吗? 如果是,我如何定义它?

我的计划是制作这样的枢轴,但是我可以在数据透视表内建立关系吗?

class RabProducts extends Pivot {
    //relation function to currency
}

并更改我的产品型号,例如:

   public function rab(){
       return $this->belongsToMany('App\ModelUnitKerja\Perencanaan\RabModel')->using('App\RabProducts');
}
  1. 创建货币模型并添加 foreign_key product_id
php artisan make:model Currency
  1. 在 Product 和 Currency 之间建立一对多,您需要在您的currencies表中添加product_id

在您的货币模型中:

    public function product() {
      return $this->belongsTo('App\Product', 'product_id');
    }

在您的产品型号中:

    public function currencies()
    {
        return $this->hasMany(\App\Currency::class, 'product_id', 'id');
    }

这样你就可以这样称呼它:

RAB::with(['products' => function($query) {
    $query->with('currencies');
}])->get();

不幸的是, productsrabs之间的foreign_key 在数据透视表中,你不能直接用货币创建hasmanythrough

您可以按产品调用货币。 或者您可以创建一个枢轴模型,然后使用hasmanythrough

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM