Wednesday, March 15, 2017

laravel - query with foreign key

Welcome ! I have two tables in database notes and pilots and i want to display notes which belongs to pilots. I added foreign key to notes table but i have such problem when i try to create new note:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`app`.`notes`, CONSTRAINT `notes_pilot_id_foreign` FOREIGN KEY (`pilot_id`) REFERENCES `pilots` (`id`))

Note model:

 class Note extends Model
    {
      protected $table = 'notes';
        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
            'data', 'zadanie', 'uwagi', 'pilot_id',
        ];

        public function pilot() {
          return $this->belongsTo(Pilot::class);
        }
    }

Pilot model:

class Pilot extends Model
{
  protected $table = 'pilots';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'phone', 'email',
    ];

    public function note() {
      return $this->hasMany(Note::class);
    }
}

Note controller store method:

public function store(Request $request)

{

    $this->validate($request, [

        'data' => 'required',

        'zadanie' => 'required',

        'uwagi' => 'required',

    ]);


    $note = new Note (array(
      'data' => $request->get('data'),
      'zadanie' => $request->get('zadanie'),
      'uwagi' => $request->get('uwagi'),

    ));
    $note->save();
    $note->pilot()->sync($request->get('pilots'));

    return redirect()->route('uwagi.index')

                    ->with('success','Uwagi dodane poprawnie');

}



via tomczas

Advertisement