【问题标题】:How to achieve attach/detach like structure for oneToMany relationship?如何为 oneToMany 关系实现类似结构的附加/分离?
【发布时间】:2019-03-04 12:31:10
【问题描述】:

例如。 Region 和 City 是两个模型。关系定义如下:

Region.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Region extends Model
{
    public function cities() {
        return $this->hasMany('App\City');
    }
}

City.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class City extends Model
{
    public $timestamps = false;

    public function region() {
        return $this->belongsTo('App\Region');
    }
}

区域可以有多个城市,但一个城市只能与一个区域关联。为此,我有一个已经添加的城市列表,但想在区域的详细信息页面上附加城市与区域,就像我们有多对多关系一样。 如何验证并且不允许将城市附加到已经附加到任何其他区域的区域?

【问题讨论】:

  • 仅将“未使用的城市”发送到详细信息页面。

标签: laravel laravel-5.7 laravel-nova


【解决方案1】:

您需要在模型上创建一个自定义方法来实现类似的效果。这是您可能希望如何做的示例

City.php

public function attachToRegion(Region $region) {
    if ($this->region) {
        throw new CityAlreadyAttachedException();
    }

    $this->update(['region_id' => $region->id]);
}

然后,如果城市模型已附加到区域模型,您将在您的存储库/服务/控制器中调用它并捕获异常。例如:

try {
    $region = Region::first();
    $city = City::first()->attachToRegion($region);
} catch (CityAlreadyAttachedException $e) {
    // The city is already attached. Handle the error here
}

【讨论】:

    猜你喜欢
    • 2019-08-05
    • 1970-01-01
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2015-07-31
    相关资源
    最近更新 更多