2017-08-22 20 views
0

完整性約束違規:1452無法添加或更新子行:外鍵約束失敗(projectsposts,CONSTRAINT posts_user_id_foreign FOREIGN KEY(user_id)參考文獻usersid))我需要知道帖子的所有者,通過使用引用帖子中的表用戶的外鍵

class CreatePostsTable extends Migration 
{ 
    /** 
    * Run the migrations. 
    * 
    * @return void 
    */ 
    public function up() 
    { 
     Schema::create('posts', function (Blueprint $table) { 
      $table->engine ='InnoDB'; 
      $table->increments('id'); 
      $table->string('jobtitle'); 
      $table->string('location'); 
      $table->string('jobtype'); 
      $table->string('jobdesc'); 
      $table->string('companyname'); 
      $table->string('howto'); 
      $table->integer('user_id')->unsigned(); 
      $table->timestamps(); 
     }); 

     Schema::table('posts', function($table) {                        
      $table->foreign('user_id')->references('id')->on('users'); 
     }); 
    } 

    /** 
    * Reverse the migrations. 
    * 
    * @return void 
    */ 
    public function down() 
    { 
     Schema::dropIfExists('posts'); 
    } 
} 

Post模型

class Posts extends Model 
{ 
    // 
    protected $fillable =[ 
     'jobtitle', 
     'location', 
     'jobtype', 
     'jobdesc', 
     'companyname', 
     'howto', 
     'user_id' 
    ];    

    protected $guarded = array(); 

    public static $rules = array(); 

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

用戶模型

public function posts() 
{ 
    return $this->hasMany('App\Posts','user_id '); 
} 
+0

我是laravel的新手 –

+0

您的錯誤確實與Laravel無關,這是一個SQL錯誤,意味着您在插入時指定的posts.user_id不存在於users.id – Devon

+0

您嘗試嘗試時發生此錯誤將數據插入表中? – ryantxr

回答

0

你並不需要聲明在MySQL側的外鍵,你必須至少創建一個user_id列(你確實有)將由Laravel被用作外鍵。

要獲得創建帖子的用戶只需引用關係。

$owner = \App\Post::user->name; // get the user who created the post. 
0

你的表定義告訴MySQL的,它必須posts.user_id一個值,該值必須在用戶表中的列id存在。這是基本的參照完整性。

假設表的用戶有以下幾點:

| id | name  | 
| 1 | Josie | 
| 2 | Jeff  | 

那麼下面插入到表posts,因爲表users沒有與ID對應的用戶5

INSERT INTO posts 
    (`jobtitle`, 
    `location`, 
    `jobtype`, 
    `jobdesc`, 
    `companyname`, 
    `howto`, 
    `user_id`) 
    VALUES (
    'manager', 
    'some city', 
    'cook', 
    'cooks food', 
    'Very good restaurants', 
    'How we do things', 
    5) 

爲了解決將失敗這個,你必須確定之前的用戶你試圖插入表posts並正確設置user_id列。

+0

我有一個現有的用戶誰在會議中,並希望張貼,這意味着存在他的ID,我參考,我如何確定用戶,但有人不能創建一個職位沒有登錄。 –

+0

我知道?您尚未發佈任何代碼或與之相關的任何內容。也許那是在會議中? – ryantxr

+0

您可以使用Auth :: user()來確定它 – Wreigh

相關問題