Laravel - Eloquent

Laravel - Eloquent

我的数据库中有以下 tables:

连接
编号
owner_id

所有者
编号
room_id

房间
编号
room_number

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

中加入什么样的关系

如果我没理解错的话,你有连接 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');

我明白了。我必须在 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 抱歉打扰了。