用于创建REST API的Laravel 5.4级联不起作用(也不工作一对多关系)

时间:2017-02-13 20:23:50

标签: php mysql laravel rest laravel-5.4

检查我的代码,我使用laravel 5.4创建REST API,使用Mysql使用一对多的关系,帮我找出错误

我的迁移代码表&帐户模型(用户有很多帐户)

<?php
 class CreateAccountsTable extends Migration
{

public function up()
{
    Schema::create('accounts', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned()->index();
        $table->string('bank_name');
        $table->string('ac_no');
        $table->timestamps();


    });

    Schema::table('accounts', function($table) {
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}
public function down()
{
    Schema::dropIfExists('accounts');

    Schema::table('accounts', function($table) {
        $table->dropForeign('accounts_user_id_foreign');
    });
}

}

帐户模型

class Accounts extends Model
 {
       protected $fillable =[
         'bank_name','ac_no'
       ];
   public function useraccounts()
   {
     return $this->belongsTo('App\User','user_id');
  }
 }

用户表迁移代码&amp;模型用户有很多帐户

表格代码

class CreateUsersTable extends Migration
{
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email',191)->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}


public function down()
{
    Schema::dropIfExists('users');
}
}

用户模型

class User extends Authenticatable
{
  public function accounts()
{
    return $this->hasMany('App\Accounts');
}
// this is a recommended way to declare event handlers
protected static function boot() {
    parent::boot();

    static::deleting(function($user) { // before delete() method call this
        $user->accounts()->delete();
        // do the rest of the cleanup...
    });
}
}

我的控制器

 // One to many relationship

public function one_to_many(Request $request)
{
    $v = Validator::make($request->all(),[
        'bank_name'=>'required',
        'ac_no'=>'required',
        'user_id'=>'required'
    ]);

    $user_id = $request->input('user_id');
    $bankname = $request->input('bank_name');
    $ac_no = $request->input('ac_no');

    if($v->fails())
    {
        $response = [

            'msg' => 'Check your input Error Occur',
            'status' => false,
            'reason' => $v->errors()
        ];

        return response()->json($response, 422);
    }elseif(! User::find($user_id))
    {
        $response = [

            'msg' => 'Give the correct Userid',
            'status' => false,
            'reason' => 'Cant find the user_id from DB'
        ];

        return response()->json($response, 422);
    }

   $user =  User::find($user_id)->id;

    //$get = $user->posts();

    $array = array('bank_name'=>$bankname,'ac_no'=>$ac_no);

    $savepost = Accounts::create($array);


    $savepost->useraccounts()->save($user);

    return $savepost;
}

ERROR:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`laraapirest`.`accounts`, CONSTRAINT `accounts_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE) (SQL: insert into `accounts` (`bank_name`, `ac_no`, `updated_at`, `created_at`) values (adasdasd, 11111, 2017-02-13 20:07:34, 2017-02-13 20:07:34))



PDOException in Connection.php line 449:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a       child row: a foreign key constraint fails (`laraapirest`.`accounts`, CONSTRAINT `accounts_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE)

3 个答案:

答案 0 :(得分:0)

您未在控制器中的此行传递用户ID:

$array = array('bank_name'=>$bankname,'ac_no'=>$ac_no);

$savepost = Accounts::create($array);

您需要传递它,因为create()将尝试写入数据库。

另一种选择是使用Account运算符初始化new,并传递变量:

$array = array('bank_name'=>$bankname,'ac_no'=>$ac_no);

$savepost = new Accounts;
$savepost->bank_name = $bankname
....

$savepost->useraccounts()->save($user);

答案 1 :(得分:0)

$savepost = Accounts::create($array);替换为$savepost = new Accounts($array)

并将$savepost->useraccounts()->save($user);替换为$user->accounts()->save($savepost);

答案 2 :(得分:0)

答案在许多方法中使用关系中的关联,因为它们具有该模型的集合并且属于其他模型

答案是

$savepost->useraccounts()->associate($user);
$savepost->save();