serii81
@serii81
Я люблю phр...

Как решить «SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null » в ларавель?

Я не могу заполнить таблицу поставить через фабрику и не могу понять где ошибка, почему user_id === null, если я его добавил в модель поста в $fillable.
Ларавель 7.
Миграция создания постов.
public function up()
    {
        Schema::create('blog_posts', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('category_id');
            $table->unsignedInteger('user_id');
            $table->string('title');
            $table->string('slug')->unique();
            $table->text('excerpt')->nullable();
            $table->text('content_raw');
            $table->text('content_html');
            $table->boolean('is_published')->default(false)->index();
            $table->timestamp('published_at')->nullable();
            $table->foreign('category_id')->references('id')->on('blog_categories');
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
    }

Модель поста
class BlogPost extends Model
{
    protected $fillable = [
        'title',
        'slug',
        'category_id',
        'excerpt',
        'content_raw',
        'content_html',
        'user_id',
        'is_published',
        'published_at',
        'updated_at',
        'created_at',
    ];

    public function category()
    {
        return $this->belongsTo(BlogCategory::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Фабрика поста
$factory->define(BlogPost::class, function (Faker $faker) {
    $title = $faker->sentence(rand(3, 8), true);
    $text = $faker->realText(rand(1000, 4000));
    $isPublished = rand(1, 5) > 1;
    $createdAt = $faker->dateTimeBetween('-6 months', '-1 day');

    return [
        'category_id' => rand(1, 10),
        'user_id' => rand(1, 5) === 5 ? 1 : 2,
        'title' => $title,
        'slug' => Str::slug($title),
        'excerpt' => $faker->text(rand(100, 400)),
        'content_raw' => $text,
        'content_html' => $text,
        'is_published' => $isPublished,
        'published_at' => $isPublished ? $faker->dateTimeBetween('-6 months', '-1day') : null,
        'created_at' => $createdAt,
        'updated_at' => $createdAt
    ];
});

DatabaseSeeder
public function run()
    {
        $this->call(UserTableSeeder::class);
        $this->call(BlogCategorySeeder::class);
        factory(BlogPost::class, 100)->create();
    }

И сам код ошибки.
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into `blog_posts` (`category_id`, `user_id`, `title`, `slug`, `excerpt`, `content_raw`, `content_html`, `is_published`, `published_at`, `created_at`, `updated_at`) values (5, ?, Inventore sapiente necessitatibus accusamus voluptas modi ut voluptas delectus ut., inventore-sapiente-necessitatibus-accusamus-voluptas-modi-ut-voluptas-delectus-ut, Dolor ea voluptas qui necessitatibus ut quasi quia accusamus. Nihil id similique molestiae pariatur veniam. Voluptatem voluptatem quis sapiente., Mock Turtle: 'why, if a fish came to ME, and told me you had been (Before she had tired herself out with his head!"' 'How dreadfully savage!' exclaimed Alice. 'And where HAVE my shoulders got to? And oh, my poor hands, how is it twelve? I--' 'Oh, don't bother ME,' said Alice thoughtfully: 'but then--I shouldn't be hungry for it, you may nurse it a violent blow underneath her chin: it had been, it suddenly appeared again. 'By-the-bye, what became of the what?' said the Caterpillar. 'Well, I never understood what it was: at first was in confusion, getting the Dormouse again, so that they must needs come wriggling down from the Gryphon, 'you first form into a sort of idea that they had at the Mouse's tail; 'but why do you like to be seen: she found it so quickly that the cause of this pool? I am now? That'll be a walrus or hippopotamus, but then she walked sadly down the chimney close above her: then, saying to herself 'It's the Cheshire Cat sitting on the ground as she swam nearer to watch them, and then keep tight hold of this rope--Will the roof of the Mock Turtle in a great many more than nine feet high. 'Whoever lives there,' thought Alice, 'as all the jurors were writing down 'stupid., Mock Turtle: 'why, if a fish came to ME, and told me you had been (Before she had tired herself out with his head!"' 'How dreadfully savage!' exclaimed Alice. 'And where HAVE my shoulders got to? And oh, my poor hands, how is it twelve? I--' 'Oh, don't bother ME,' said Alice thoughtfully: 'but then--I shouldn't be hungry for it, you may nurse it a violent blow underneath her chin: it had been, it suddenly appeared again. 'By-the-bye, what became of the what?' said the Caterpillar. 'Well, I never understood what it was: at first was in confusion, getting the Dormouse again, so that they must needs come wriggling down from the Gryphon, 'you first form into a sort of idea that they had at the Mouse's tail; 'but why do you like to be seen: she found it so quickly that the cause of this pool? I am now? That'll be a walrus or hippopotamus, but then she walked sadly down the chimney close above her: then, saying to herself 'It's the Cheshire Cat sitting on the ground as she swam nearer to watch them, and then keep tight hold of this rope--Will the roof of the Mock Turtle in a great many more than nine feet high. 'Whoever lives there,' thought Alice, 'as all the jurors were writing down 'stupid., 1, 2022-01-11 19:20:20, 2021-08-09 14:30:12, 2021-08-09 14:30:12))

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:671
    667|         // If an exception occurs when attempting to run a query, we'll format the error
    668|         // message to include the bindings with SQL, which will make this exception a
    669|         // lot more helpful to the developer instead of just the database's errors.
    670|         catch (Exception $e) {
  > 671|             throw new QueryException(
    672|                 $query, $this->prepareBindings($bindings), $e
    673|             );
    674|         }
    675| 

      +19 vendor frames 
  20  database/seeds/DatabaseSeeder.php:17
      Illuminate\Database\Eloquent\FactoryBuilder::create()

      +34 vendor frames 
  55  artisan:37
      Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
  • Вопрос задан
  • 254 просмотра
Пригласить эксперта
Ответы на вопрос 1
Ukrainskiy
@Ukrainskiy
$table->foreign('user_id')->references('id')->on('users');

А юзер точно есть с таким id?
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы