【问题标题】:Not sure how to setup these database tables in Laravel不确定如何在 Laravel 中设置这些数据库表
【发布时间】:2021-10-13 16:38:41
【问题描述】:

将首先创建周末表,因此我认为周末蒸汽 ID 需要在周末并执行选择语句。但我真的很困惑。基本上用户将进入一个周末。然后以不同的观点,他们将进入那个周末的团队。我需要找到一种方法将这两个表绑定在一起,这样我就可以在前端查询它以获取周末视图。

周末餐桌

    Schema::create('weekends', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->mediumText('verse');
            $table->string('songtitle');
            $table->string('songvideo');
            $table->string('image')->default('default.png');
            $table->string('videolink')->nullable();
            $table->timestamps();
        });

周末团队

    Schema::create('weekendteam', function (Blueprint $table) {
            $table->id();
            $table->string('firstname');
            $table->string('lastname');
            $table->string('position');
            $table->timestamps();
        });

【问题讨论】:

    标签: laravel join eloquent


    【解决方案1】:

    这听起来很适合一对多关系。由于看起来您将团队成员及其位置存储在 weekendteam 表中,因此您可以简单地添加一个 weekend_id 列(我还将表重命名为 weekend_team_members):

    Schema::create('weekend_team_members', function (Blueprint $table) {
        $table->id();
        $table->foreignId('weekend_id');
        $table->string('firstname');
        $table->string('lastname');
        $table->string('position');
        $table->timestamps();
    });
    

    然后,为了让团队参加任何周末,您可以使用如下查询:

    SELECT * FROM weekend_team_members WHERE weekend_id = 1;
    

    这将获取具有该 ID 的周末所有团队成员。如果您使用 Eloquent 模型,您还可以使用它们的内置关系来简化查询:

    class Weekend extends Model {
    ...
    
        public function weekendTeamMembers() {
            return $this->hasMany(WeekendTeamMember::class);
        }
    }
    
    class WeekendTeamMember extends Model {
    ...
    
        public function weekend() {
            return $this->belongsTo(Weekend::class);
        }
    }
    

    在模型中定义这些关系后,您可以使用它们来帮助您查询数据。例如,如果您在变量$weekend 中已经有一个Weekend,您可以像这样获取所有团队成员:

    $teams = $weekend->weekendTeamMembers;
    

    或者,如果您有团队成员,您可以像这样度过周末:

    $weekendTeamMember->weekend;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-26
      • 2021-03-07
      • 1970-01-01
      • 2018-02-14
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      相关资源
      最近更新 更多