首页 文章

插入db时的laravel修补程序

提问于
浏览
1

我正在创建一个新的Web应用程序,其中有3个表: usersteamsproject

这是 teamproject 迁移结构:

Schema::create('teams', function (Blueprint $table) {
    $table->increments('id');
    $table->string('team_image', 15);
    $table->string('team_name', 50);
    $table->string('team_description');
    $table->timestamps();
});

Schema::create('project', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('members')->unsigned();
    $table->foreign('members')->references('id')->on('teams');
    $table->string('name');
    $table->string('description');
    $table->string('lead');
    $table->timestamps();
});

这是 TeamProject 模型:

class Team extends Model
{
    protected $table = 'teams';

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

class Project extends Model
{
    protected $table = 'project';
    protected $fillable = ['name', 'description'];

    public function teams()
    {
        return $this->belongsTo('App\Team');
    }
}

修补我运行这个:

$team = factory('App\Team')->create();

而且我已经填充了db faker mumbo jumbo,那没关系 . 但是当我尝试调用该项目时:

$team->projects()->create(['name'=>'project 1', 'description'=>'bla bla']);

我明白了:

Illuminate \ Database \ QueryException,消息'SQLSTATE [42S22]:未找到列:1054'字段列表'中的未知列'team_id'(SQL:插入项目(名称,描述,team_id,updated_at,created_at)值(项目1) ,bla bla,2,2015-12-20 00:06:29,2015-12-20 00:06:29))'

team_id 用于代替 members ,在之前的一些迁移中使用过,但我重新安装了迁移并更新了迁移文件并重新运行迁移,db很好,创建了 members 列 .

当我用 team_id 替换 members 时,修补程序工作并将名称插入 project 表 .

有什么线索吗?

1 回答

  • 1

    关系代码不知道任何数据库级别信息,例如外键约束 . 这是因为迁移仅用于创建表,它们与实际模型没有任何关联 .

    相反,外键的关系使用标准命名约定 . 它由附加字符串 _id 的相关模型的小写名称(在您的情况下为 team )组成 . 因此它以 team_id 结束,这就是当列以这种方式命名时它起作用的原因 . 如果希望外键列具有非标准名称(例如 members ),则需要在定义关系时指定:

    class Team extends Model
    {
        protected $table = 'teams';
    
        public function projects()
        {
            return $this->hasMany('App\Project', 'members');
        }
    }
    

    one-to-many relationships上的Laravel文档解释了在需要时,您可以将另外两个参数传递给 hasMany 方法,外键和本地键列名称 .

相关问题