【问题标题】:SQLSTATE[42S02]: Base table or view not found: 1146 error laravelSQLSTATE [42S02]:未找到基表或视图:1146 错误 laravel
【发布时间】:2019-04-08 08:07:24
【问题描述】:

我已经尝试解决一个问题几个小时了。

基本上我得到了:

SQLSTATE[42S02]:未找到基表或视图:1146 表 'tp-laravel.image_location' 不存在(SQL:从 image_location 中选择 location_id 其中image_id = 3)错误。

这是否来自错误的控制器/模型/迁移?当我尝试在我的网站中添加图片时会发生这种情况。

我一直在尝试更改内容、添加内容并在 google 上查找了很多内容,但没有任何解决方法。

Image.php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class Image extends Model
{
    protected $fillable = ['name'];

    public function locations()
    {
        return $this->belongsToMany(Location::class);
    }

    public function getUpdatedAtAttribute($date)
    {
        return Carbon::parse($date)->locale('fr')->diffForHumans(Carbon::now());
    }
}

Location.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Location extends Model
{
    protected $fillable = ['name'];

    public function locations()
    {
        return $this->belongsToMany(Image::class);
    }
}

以下是我的控制器中的创建和存储方法:

    public function create()
    {
        $locations = Location::pluck('name', 'id');
        $users = User::pluck('name', 'id');
        return view('posts.create', compact('locations'));
    }

    public function store(Request $request)
    {
        $image = Image::create(request()->all());
        $image->locations()->sync(request()->get('locations'));
        $user->users()->sync(request()->get('users'));
        return redirect('/accueil');
    }

最后是我的图像迁移

    Schema::create('images', function (Blueprint $table) {
            $table->bigIncrements('id');

            $table->BigInteger('location_id')->unsigned()->index();

            $table->BigInteger('user_id')->unsigned()->index();

            $table->foreign('location_id')->references('id')->on('locations')->onDelete('cascade');

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

            $table->string('name', 100);

            $table->timestamps();
        });

当我在视图中按下创建按钮时,提交它应该将图像添加到数据库中,并将用户和位置链接到它作为外键,但弹出上述错误。

谢谢!

【问题讨论】:

    标签: laravel


    【解决方案1】:

    错误来自

        public function locations()
        {
            return $this->belongsToMany(Location::class);
        }
    

    Laravel 假设你有一个按字母顺序命名的中间表,因为它是image_location,并且这个表在你的数据库中不存在。

    唯一的方法是创建这样的表,或者如果你创建了不同名称的表,你可以传递第二个参数作为表名。于是就变成了:

        public function locations()
        {
            return $this->belongsToMany(Location::class, 'TABLE_NAME');
        }
    

    【讨论】:

      猜你喜欢
      • 2018-03-16
      • 2016-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-21
      • 2020-06-26
      相关资源
      最近更新 更多