2015-12-20 47 views
1

我创建一个新的网络应用,在那里我有3个表:usersteamsprojectlaravel鼓捣当插入到数据库

这里是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'); 
    } 
} 

In修补程序我运行这个:

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

而且我得到了人口稠密的数据库的福克博士珍宝,这就好了。但是,当我试图把这个项目:

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

我得到这个:

照亮\数据库\ QueryException与消息“SQLSTATE [42S22]: 列未找到:1054未知列 'TEAM_ID'在 '字段列表'(SQL: 插入到projectnamedescriptionteam_idupdated_atcreated_at)值(项目1,血乳酸血乳酸,2,2015年12月20日0时06分29秒, 2015-12- 20 00:06:29))'

而且team_id代替members,在前面几个迁移使用,但我已经reseted迁移和更新迁移文件并重新运行迁移和DB是罚款,创建members列。

当我将members替换为team_id时,修补程序工作并将名称插入到project表中。

任何线索?

回答

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方法,外键和本地键列名称。

+0

感谢波格丹,我需要更多的阅读,所以这帮助了我很多,并解决了这个问题。 TNX – pinarella