Laravel - 雄辩

问题描述 投票:-1回答:2

我的db中有以下表格: 连接 ID owner_id

拥有者 ID ROOM_ID

客房 ID 房间号

我想通过owner_id从我的连接表中引用room_number。我尝试使用hasManyThrough关系,但它以相反的方式工作(从房间表到连接表中的字段)。我应该如何建立关系以及我应该在App \ Connections中添加什么样的关系?

php mysql laravel laravel-eloquent
2个回答
0
投票

如果我理解正确,你有连接ID,你想获得房间号码。

首先,定义关系。在Room模型:

public function owners()
{
    return $this->hasMany(Owner::class);
}

Owner模型:

public function connections();
{
    return $this->hasMany(Connection::class);
}

要通过连接ID获取房间号码:

$connectionIds = [12, 15, 20];
$roomNumbers = Room::whereHas('owners.connections', function($q) use($connectionIds) {
        $q->whereIn('id', $connectionIds);
    })->pluck('room_number');

0
投票

我懂了。我不得不在Apps中加入以下关系: Connections.php

public function owners()
{
    return $this->belongsTo('App\Owners', 'owner_id');
}

Owners.php

public function connections()
{
    return $this->hasMany('App\Connections');
}

public function rooms()
{
    return $this->belongsTo('App\Rooms', 'room_id');
}

Rooms.php

public function owners()
{
    return $this->hasMany('App\Owners');
}

现在我在下面添加了一行到我的ConnectionsController.php

$connections = Connections::with('owners')->paginate(5);

我可以在我的index.blade写中引用:

@foreach($connections as $element)
    {{ $element->owners->rooms->room_number }}
@endforeach

@AlexeyMezenin对不起大惊小怪。

© www.soinside.com 2019 - 2024. All rights reserved.