2015-12-20 46 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