SQLSTATE [HY000]: общая ошибка: 1364 Поле 'uID' не имеет значения по умолчанию - PullRequest
0 голосов
/ 08 декабря 2018

только что начался с Laravel.Я приложил свои модели пользователя и профиля вместе с контроллером профиля.Моя цель - автоматически назначить uID внешнего ключа в таблице profile .Мы будем благодарны за любую помощь.

файл модели пользователя

namespace App;

use Illuminate\Database\Eloquent\Model;

class user extends Model
{
    // specify which attributes can be filled out during registration
    public $timestamps = false;
    protected $fillable=['firstname','lastname','email','password',];

    public function profile(){
      return $this->hasOne(profile::class,'pID','uID');
    }
}

файл модели профиля

namespace App;

use Illuminate\Database\Eloquent\Model;

class profile extends Model
{
    //
    public $timestamps = false;
    protected $fillable = ['summary','uID'];

    public function user(){
      return $this->belongsTo(user::class,'uID','pID');
    }
}

файл миграции профиля

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProfilesTable extends Migration
{
    public function up()
    {
      // create profile table
        Schema::create('profiles', function (Blueprint $table) {
            $table->increments('pID');
            $table->timestamp('created_at')->useCurrent();
            $table->string('summary')->default('');
            $table->integer('uID')->unsigned();

            $table->foreign('uID')->references('uID')->on('users')->onDelete('cascade');
        });
    }
}

файл контроллера профиля

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\profile;

class ProfileController extends Controller
{
    public function store(Request $request)
    {
       // used to store user profile after validation
        $this->validate($request,[
          'summary' => 'required'
        ]);
        $profile = new profile([
          'summary' => $request->get('summary'),
        ]);
        $profile->save();

        return redirect()->route('profile.create')->with('success','Profile created');
    }
}

Ответы [ 2 ]

0 голосов
/ 08 декабря 2018

Измените файл миграции, так как вы хотите определить свои отношения позже, поэтому поле внешнего идентификатора должно быть пустым.

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProfilesTable extends Migration
{
public function up()
{
// create profile table
Schema::create('profiles', function (Blueprint $table) {
$table->increments('pID');
$table->timestamp('created_at')->useCurrent();
$table->string('summary')->default('');
$table->integer('uID')->nullable()->unsigned();

$table->foreign('uID')
        ->references('uID')
        ->on('users')
        ->onDelete('cascade');
});
}
}

И если вы хотите назначить зарегистрированного пользователя после создания профиля,

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\profile;

class ProfileController extends Controller
{
    public function store(Request $request)
    {
       // used to store user profile after validation
        $this->validate($request,[
          'summary' => 'required'
        ]);
        $profile = new profile([
          'summary' => $request->get('summary'),
          'uID'     => auth()->user()->id,

        ]);
        $profile->save();

        return redirect()->route('profile.create')->with('success','Profile created');
    }
}
0 голосов
/ 08 декабря 2018

Если вы не предоставляете значение в своей программе, вам нужно указать значение по умолчанию на уровне определения таблицы.

Согласно вашему описанию, вам кажется, что вам не хватает создать профиль после создания пользовательской записи.

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