【问题标题】:Deleting many to many row eloquent删除多对多行雄辩
【发布时间】:2018-02-17 12:14:56
【问题描述】:

我将 Laravel 5.5Mysql 一起使用。我有下一个数据库设计(所有设计的一部分)。而且我不知道如何删除 Connecta 的一行(多对多关系),并根据该连接的客户端数量,也删除该连接。

基数:

  • 1 个客户端可以有很多连接 (Connexio),每个连接一个价格 (Tarifa)。
  • 1 个连接 (Connexio) 可以有很多客户,每个客户一个价格 (Tarifa)
  • 1 个价格 (Tarifa) 可以分配给许多连接和客户端
  • 对于每个连接和客户端,我们有一个方向 (Direccio)

如果我们想撤销来自客户端的连接,我们有两种可能性:

  1. 连接只有一个客户端:

    • 我们删除行关系Connecta,删除连接和方向的连接。
  2. 连接有多个客户端:

    • 我们只删除了Connecta的行关系

Connexio 的 Eloquent 关系:

public function clients()
    {
        return $this->belongsToMany(Client::class,'connecta')->withPivot('estat', 'id')->withTimestamps();
    }

客户的雄辩关系:

public function connexions()
    {
        return $this->belongsToMany(Connexio::class,'connecta')->withPivot('estat', 'id')->withTimestamps();
    }

如何在单个控制器上实现这两种可能性?

【问题讨论】:

  • 首先属于许多我认为这是错误的关系。正确的关系将是 hasManyThrough 和 price 将是调解人..查看此文档,您将了解..laravel.com/docs/5.6/eloquent-relationships#has-many-through
  • @DhavalChheda 感谢您的更正。我不知道那种 Eloquent 关系。
  • 如果你设置了外键,那么你可以删除它和它的依赖数据。

标签: php database laravel eloquent many-to-many


【解决方案1】:

我所做的是使用belongsToMany 关系,因为我可以获得数据透视列,而我无法使用hasManyThrough 关系。

Connexio 型号:

public function clients()
{
    return $this->belongsToMany(Client::class,'connecta')->withPivot('tarifa_id', 'estat', 'id')->withTimestamps();
}

在控制器中,我根据连接分配的客户端数量执行不同的操作:

public function destroy(ConnexioDestroy $request, Connexio $connexio, Client $client)
{
    try {
        if (count($connexio->clients) == 1) {
            // If connection only have one client we delete the relation,
            // the connection and the address of the connection
            $connecta = Connecta::findOrFail($connexio->clients[0]->pivot->id);
            $connecta->delete();
            $direccio = $connexio->direccio;

            $connexio->delete();
            $direccio->delete();
        } else {
            // If connection has more than 1 client delete only
            // the relation between the client and the connection
            for ($i = 0; $i < count($connexio->clients); $i++) {
                if ($client->id == $connexio->clients[$i]->pivot->client_id) {
                    $connecta = Connecta::findOrFail($connexio->clients[$i]->pivot->id);
                    $connecta->delete();
                }
            }
        }
    } catch (ModelNotFoundException $e) {
        // No relation between connection and client founded
        abort(422, 'No s\'ha trobat la relació entre la connexió i el client');
    }
}

它对我有用

【讨论】:

    猜你喜欢
    • 2013-09-26
    • 2014-10-08
    • 1970-01-01
    • 2020-03-11
    • 2014-05-23
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多