3

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

区域.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Region extends Model
{
    public function cities() {
        return $this->hasMany('App\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');
    }
}

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

4

1 回答 1

0

您需要在模型上创建一个自定义方法来实现这样的目标。这是您可能希望如何执行此操作的示例

城市.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
}
于 2018-09-28T14:47:02.723 回答