【问题标题】:Laravel storing model with foreign keys带有外键的 Laravel 存储模型
【发布时间】:2018-06-04 13:35:42
【问题描述】:

我正在尝试存储一个模型,它是一个链接表。 表:

Schema::create('game_has_users', function (Blueprint $table) {
        $table->integer('game_id')->unsigned();
        $table->integer('user_id')->unsigned();
        $table->foreign('game_id')->references('id')->on('games')->onUpdate('cascade')->onDelete('cascade');
        $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
        $table->timestamps();
    });

Game_Has_Users 模型:

     class Game_Has_Users extends Model
{
    protected $table = 'game_has_users';

    public function user()
    {
        return $this->hasOne('App\User', 'user_id');
    }

    public function game()
    {
        return $this->hasOne('App\Game', 'game_id');
    }
}

我想存储一个游戏,然后,应该使用用户 ID 和游戏 ID 创建 Game_Has_Users 模型。

try {
      $game = Game::create([]);
      $user = User::where('name', $request->input('name'))->first();

//      $game_users = Game_Has_Users::create([]);
//      $game_users->user = $user->id;
//      $game_users->game = $game->id;
//      $game_users->save();

      $test = Game_Has_Users::create([
          'user_id' => $user->id,
          'game_id' => $game->id
      ]);
      return response()->json(['t' => $test, 'status' => 'ok']);
    }
    catch(\Exception $e) {
      return response()->json(['status' => 'failed', 'message' => $e]);
    }

但是,我总是收到以下响应:状态:失败,消息:[]。 它没有例外,所以我不知道我做错了什么。 我尝试了不同的方法,例如:为游戏 ID 和用户 ID 设置默认值,保存链接模型的不同方法。当我通过响应发送 $game->id 和 $user->id 时,它们确实有一个值。

【问题讨论】:

  • Game_Has_Users 不应该是模型。这是一个数据透视表。您在游戏和用户之间存在多对多关系,因此请在您的游戏和用户模型中定义它。

标签: php mysql laravel laravel-5 eloquent


【解决方案1】:

你应该设置$fillable属性;

protected $fillable = ['user_id', 'game_id'];

在您的 Game_Has_Users 模型中

【讨论】:

    【解决方案2】:

    符合 Eloquent

    Eloquent 期望每个表都有一个主键,因此请确保向该表添加一个 id 列。如果没有这个专栏,你在使用各种雄辩的方法时会遇到问题。

    在您的迁移中,这将添加一个自动递增的主键:

    $table->increments('id');
    

    利用关系

    接下来,如果我没记错的话,Games_Has_Users 看起来像是多对多关系。

    因此,您不需要此表的模型。使用适当的 belongsToMany 关系,您可以将模型彼此附加:

    $game = Game::find(1);
    $user = User::find(1);
    // Assuming the User model has a games() belongsToMany relationship;
    $user->games()->attach($game);
    // or the inverse
    $games->users()->attach($user);
    

    然后您可以使用$user->games 访问附加到用户的游戏集合。

    阅读https://laravel.com/docs/5.5/eloquent-relationships#many-to-many

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-31
      相关资源
      最近更新 更多