如何实现一对多关系的类似attach/detach结构?

3
例如,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');
    }
}

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


仅向详细页面发送“未使用的城市”。 - Tharaka Dilshan
1个回答

0
你需要在模型上创建一个自定义方法来实现这样的功能。以下是一个示例,演示了如何实现它。

City.php

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

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

您可以在您的 repository/service/controller 中调用此方法,并捕获异常,以防城市模型已附加到区域模型中。例如:
try {
    $region = Region::first();
    $city = City::first()->attachToRegion($region);
} catch (CityAlreadyAttachedException $e) {
    // The city is already attached. Handle the error here
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接