【问题标题】:Doubts with laravel relationship对laravel关系的怀疑
【发布时间】:2023-03-09 21:40:01
【问题描述】:

我制作这个架构是为了将特定季节的价格保存在特定板中

示例:Hotel X 八月半食宿 50 欧元,全食宿 50 欧元 ...

    Schema::create('boards', function (Blueprint $table) {
        $table->engine = "InnoDB";
        $table->increments('id');
        $table->string('name', 45);
    });

    Schema::create('seasons', function (Blueprint $table) {
        $table->engine = "InnoDB";
        $table->increments('id');
        $table->string('name', 45);
    });

    Schema::create('hotels', function (Blueprint $table) {
        $table->engine = "InnoDB";
        $table->increments('id');
        $table->string('name', 45);
        $table->string('city');
        $table->unsignedInteger('agency_id');

        $table->foreign('agency_id')->references('id')->on('agencies');

        $table->timestamps();
    });

    Schema::create('hotel_schedules', function (Blueprint $table) {
        $table->engine = "InnoDB";
        $table->increments('id');
        $table->unsignedInteger('hotel_id');
        $table->unsignedInteger('board_id');
        $table->unsignedInteger('season_id');
        $table->decimal('price', 7, 2);

        $table->foreign('hotel_id')->references('id')->on('hotels');
        $table->foreign('board_id')->references('id')->on('boards');
        $table->foreign('season_id')->references('id')->on('seasons');
        $table->timestamps();
    });

在模型 Boards、Seasons 和 Hotels 之间添加关系的正确方法是什么? 创建另一个模型调用 HotelSchedule 是否正确?

谢谢

【问题讨论】:

  • 我认为创建中间表 hotel_schedules 是正确的,因为这就是这些表相关的地方。

标签: laravel eloquent relationship


【解决方案1】:

Boards 和 schedule 具有多对多的关系,因此您通常应该有一个数据透视表 board_schedule 和一个相应的模型 BoardSchedule,从您上面的解释看来,一个 board 可以有多个 schedule,一个 schedule 可以有多个 board。

Board season是一对多的关系,一个board只能有一个season,但是一个season可以属于多个boards,seasons hotel是多对多的,因为一个season可以有多个hotel,一个hotel可以属于多个seasons . 在您的 BoardSchedule 模型上,您应该有这样的东西

public function Schedule(){
    return $this->belongsToMany('App\Schedule')
        ->withPivot('hotel_schedule', 'board_id');
}

public function Board(){
     return $this->belongsToMany('App\Board')
    ->withPivot('hotel_board', 'schedule_id');
}

一个 Schedule 也可以有许多酒店,一个酒店可以属于多个 schedule ,所以就像上面一样,在您的 HotelSchedule 模型上也是多对多

public function Schedule(){
    return $this->belongsToMany('App\Schedule')
        ->withPivot('hotel_schedule', 'hotel_id');

}
public function Hotel(){
    return $this->belongsToMany('App\Schedule')
       ->withPivot('hotel_schedule', 'schedule_id');
}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    相关资源
    最近更新 更多