【问题标题】:Has Many Through where the middle table has both forain keys in laravel 5.6在 laravel 5.6 中中间表有两个外键的地方有很多通过
【发布时间】:2018-03-21 19:15:22
【问题描述】:

我需要建立一个 HasManyThough 关系,其中中间模型包含两个模型的外键。 详情如下:

迁移:

    Schema::create('carriers', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
    });

    Schema::create('shipping_zones', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
    });

    Schema::create('shipping_rates', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->integer('shipping_zone_id')->unsigned()->index();
        $table->integer('carrier_id')->unsigned()->index();
        $table->decimal('rate', 20, 6);
    });

现在我需要类似的东西

$carrier->shippingZone()

有什么简单的方法可以得到这个吗?

【问题讨论】:

    标签: has-many-through laravel-eloquent belongs-to laravel-5.6


    【解决方案1】:

    根据您的迁移,您需要 Many To Many 关系而不是 HasManyThough 关系。

    Carrier.php

    public function shippingZones()
        {
            return $this->belongsToMany('App\ShippingZone', 'shipping_rates);
        }
    

    您可以使用$carrier->shippingZones 访问与承运人相关的所有运输区域。

    如果您需要链接查询,您可以使用$shippingZones = $carrier->shippingZones()->orderBy('id')->get(); here

    如果您需要使用 HasManyThough,则必须更改迁移。 here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-30
      • 2020-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-03
      相关资源
      最近更新 更多