Ошибка базы данных при вставке данных в БД с использованием laravel - PullRequest
0 голосов
/ 10 января 2020

Когда я вставляю данные в database.database, генерируется ошибка

SQLSTATE [23000]: нарушение ограничения целостности: 1452 Невозможно добавить или обновить дочернюю строку: ограничение внешнего ключа не выполняется

Моя схема

 public function up()
    {
        Schema::create('wallets', function (Blueprint $table) {

            $table->bigIncrements('id');

            $table->unsignedBigInteger('tutor_id');
            $table->foreign('tutor_id')->references('id')->on('tutors')->onDelete('cascade');

            $table->integer('amount');
            $table->timestamps();
        });
    }

вот моя схема репетитора:

Schema::create('tutors', function (Blueprint $table) {
            $table->bigIncrements('id');

            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

            $table->date('date_of_birth');
            $table->string('CV_file');
            $table->string('cnic');
            $table->text('description');
            $table->integer('ratePerHour');
            $table->integer('rating')->nullable();
            $table->timestamps();
        });

и вот моя схема пользователя

Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('address');
            $table->double('lat')->nullable();
            $table->double('lng')->nullable();
            $table->string('phone');
            $table->string('type');
            $table->string('gender');
            $table->string('profile_Image')->nullable(true);
            $table->boolean('admin')->default(false);
            $table->boolean('status')->default(false);
            $table->timestamp('approved_at')->nullable();
            $table->timestamp('deleted_at')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });

Код моей модели - какая функция запускается в пространстве имен PayNow () App \ Models;

use Illuminate \ Database \ Eloquent \ Model ; использовать Stripe \ Stripe;

класс Платеж расширяет Модель {/ ** * Получить запись, связанную с Платежом. * / publi c function post () {return $ this-> assignTo ('App \ Models \ Post'); }

/**
 * Get the request record associated with the Payment.
 */
public function request()
{
    return $this->belongsTo('App\Models\UserRequest');
}

/**
 * Get the wallet record associated with the Payment.
 */
    public function wallet()
    {
        return $this->belongsTo('App\Models\Wallet');
    }

    public function payNow(){
        $request = UserRequest::all();
        foreach ($request as $req) {
            $tutor = User::find($req->tutor_id);
            $pivotRow = $tutor->subject()->wherePivot('id', $req->pivot_id)->get();
            foreach ($pivotRow as $row) {
                $rate = $row->pivot->rate;
            }
            $user_id = $tutor;
            $tid = $req->tutor_id;
            $session = $req->sessionNum;
            $paymentSuccess = $session*$rate;
        }
        // Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
        \Stripe\Stripe::setApiKey('sk_test_dd1nMs2PEqbGLOF6SpsDIl0c00QPcwncXY');
// Token is created using Checkout or Elements!
// Get the payment token ID submitted by the form:
        $token = $_POST['stripeToken'];
        $charge = \Stripe\Charge::create([
            'amount' =>$paymentSuccess*160,
            'currency' => 'usd',
            'description' => 'student paument',
            'source' => $token,
        ]);
//        if ($charge) {
            $wallet = new Wallet();
            $wallet->tutor_id = $tid;
            $wallet->amount = $paymentSuccess;
            $wallet->save();
//            return true;
//        }
//        }else{
//            return false;
//        }
    }
}

Модель моего кошелька:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Wallet extends Model
{
    /**
     * Get the payment record associated with the Wallet.
     */
    protected $fillable = [
        'tutor_id','amount'
    ];
    public function payment()
    {
        return $this->hasMany('App\Models\Payment');
    }

    /**
     * Get the tutor record associated with the Wallet.
     */
    public function tutor()
    {
        return $this->belongsTo('App\Models\Tutor');
    }


}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...