【问题标题】:Base table or view not found: 1146 Table Laravel 5.7未找到基表或视图:1146 表 Laravel 5.7
【发布时间】:2019-02-03 01:14:06
【问题描述】:

当我尝试使用 Laravel 5 将数据保存到 mysql 时出现此错误,其他表单和 save() 方法工作正常,但这个:

SQLSTATE[42S02]:未找到基表或视图:1146 表“datatest.about_category”不存在(SQL:插入about_categoryabout_idcategory_id)值(11、4))

这是我的控制器存储方法:

public function store(AboutRequest $request)
{
    $about = new About();
    $about->title = $request->title;
    $about->body = $request->body;
    $about->save();
    $about->categories()->attach(request('category'));
    return redirect(route('abouts.create'));
}

这是我的模型:

关于.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class About extends Model
{
    public  $table = "abouts";
    public function categories()
    {
        return $this->belongsToMany(Category::class);
    }
}

类别.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $table = "categories";

    public  $fillable = ['id' , 'name'];

    public function abouts(){
        return $this->belongsToMany(About::class);
    }
}

关于表

public function up()
{
    Schema::create('abouts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->text('body');
        $table->timestamps();
    });
}

对于类别表

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

【问题讨论】:

    标签: laravel-5.7


    【解决方案1】:

    您的多对多关系需要三个表:aboutscategoriesabout_category。您尚未创建 about_category 表:

    Schema::create('about_category', function (Blueprint $table) {
        $table->integer('about_id')->unsigned();
        $table->integer('category_id')->unsigned();
    
        $table->foreign('about_id')->references('id')->on('abouts');
        $table->foreign('category_id')->references('id')->on('categories');
    });
    

    【讨论】:

    • 如何共享数据透视表的迁移?
    • @MahmoudKhosravi 我不明白这个问题。您是否有创建 about_category 表的迁移?
    • 不,我不会伪造运行php artisan migrate
    • 我更新了我的帖子,我有两个表和迁移。
    • 我还没有创建about_category 表。
    猜你喜欢
    • 1970-01-01
    • 2015-07-21
    • 2021-05-30
    • 2018-03-16
    • 2019-01-28
    • 2017-08-02
    • 2016-07-15
    • 1970-01-01
    • 2014-02-25
    相关资源
    最近更新 更多