Проблемы со сводной таблицей, прикрепление не работает с помощью braintree

#mysql #laravel #eloquent #laravel-7 #braintree

Вопрос:

Я пытаюсь прикрепить musician_id, sponsorship_id и end_date к сводной таблице (musician_sponsorship), но получаю эту ошибку: введите описание изображения здесь

Это функция, в которой мне нужно прикрепить данные к сводной таблице, как только оплата с помощью braintree пройдет успешно, мне нужно заполнить сводную таблицу всеми данными.

 public function payment(Request $request, Sponsorship $sponsorship) {
       
        $data = $request->all();
        // dd($data['price']);

        $gateway = new BraintreeGateway([
            'environment' => config('services.braintree.environment'),
            'merchantId' => config('services.braintree.merchantId'),
            'publicKey' => config('services.braintree.publicKey'),
            'privateKey' => config('services.braintree.privateKey')
        ]);
        
        $amount = $data['price'];
        // dd($amount);c
        $nonce = 'fake-valid-nonce';
    
        $result = $gateway->transaction()->sale([
            'amount' => $amount,
            'paymentMethodNonce' => $nonce,
            // 'customer' => [
            //     'firstName' => 'Tony',
            //     'lastName' => 'Stark',
            //     'email' => 'tony@avengers.com',
            // ],
            'options' => [
                'submitForSettlement' => true
            ]
        ]);
    
    
        if ($result->success) {
            $transaction = $result->transaction;
            // header("Location: transaction.php?id=" . $transaction->id);
            
            // $musician = Musician::with('sponsorships')->find(Auth::id());

            // $end_date = new DateTime();
            $musician = Musician::where('user_id', Auth::id())->first();

            
            $musician->sponsorships()->attach($musician, [
                'sponsorship_id' => 1, 
                'musician_id' => $musician->id, 
                'end_date' => Carbon::now()
            ]);

            return back()->with('success_message', 'Transaction successful. The ID is: '. $transaction->id);
        } else {
            $errorString = "";
    
            foreach ($result->errors->deepAll() as $error) {
                $errorString .= 'Error: ' . $error->code . ": " . $error->message . "n";
            }
    
            // $_SESSION["errors"] = $errorString;
            // header("Location: index.php");
            return back()->withErrors('An error occurred with the message: '.$result->message);
        }
    }
 

Модель спонсорства

 <?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Sponsorship extends Model
{
    protected $fillable = [
        'name', 
        'price', 
        'duration',
        'description'
    ]; 

    public function musicians() {
        return $this->belongsToMany('AppMusician'); 
    }
}
 

Модель музыканта

 <?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Musician extends Model
{
    protected $fillable = [
        'user_id', 
        'stagename',
        'slug', 
        'description',
        'bio',
        'services',
        'typology',
        'cover'
    ]; 

    public function user() {
        return $this->hasOne('AppUser'); 
    }

    public function genres() {
        return $this->belongsToMany('AppGenre'); 
    }

    public function sponsorships() {
        return $this->belongsToMany('AppSponsorship'); 
    }

    public function messages() {
        return $this->belongsToMany('AppMessage'); 
    }

    public function reviews() {
        return $this->belongsToMany('AppReview'); 
    }
}
 

Миграция сводной таблицы

 <?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

class CreateMusicianSponsorshipTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('musician_sponsorship', function (Blueprint $table) {
            $table->id();
            $table->timestamps(); 
            $table->dateTime('end_date'); 
            $table->unsignedBigInteger('musician_id'); 
            $table->foreign('musician_id')
                ->references('id')
                ->on('musicians')
                ->onDelete('CASCADE'); 

            $table->unsignedBigInteger('sponsorship_id'); 
            $table->foreign('sponsorship_id')
                ->references('id')
                ->on('sponsorships')
                ->onDelete('CASCADE');
        });
    }

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

Комментарии:

1. Скорее всего, в вашей таблице спонсорства нет записи со значением 1 в качестве идентификатора