插入一对一多态关系时'field list'中未知列'imageable_type' 拉拉维尔 5



我的 image 迁移

class CreateImagesTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('images', function (Blueprint $table) {
        $table->increments('id');
        $table->string('url');
        $table->integer('imageable_id');
        $table->string(' imageable_type');
        $table->timestamps();
    });
}
/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('images');
}
}

我的图像模型

class Image extends Model
{
/**
 * Get the store of the image
 */
public function store()
{
    return $this->morphTo('AppStore', 'imageable');
}
/**
 * Get the item of the image
 */
public function item()
{
    return $this->morphTo('AppItem', 'imageable');
}
/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'url', 'imageable_id', 'imageable_type'
];
}

我的商店模型

class Store extends Model
{
/**
 * Get the user that owns the store.
 */
public function user()
{
    return $this->belongsTo('AppUser');
}
/**
 * Get the items of a store
 */
public function items()
{
    return $this->hasMany('AppItem');
}
/**
 * Get the store's image.
 */
public function image()
{
    return $this->morphOne('AppImage', 'imageable');
}
/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'address', 'description','user_id',
];
}

因此,我有商店,项目,图像模型和商店/一个项目只能拥有一个图像。

我试图保存商店,图像属于storecontroller的"商店"动作中的该商店:

public function store(Request $request){
    $request->validate(....);
    $store = $user->stores()->create($request->all());
    // Upload the image to s3 and retrieve the url
    ...
    $url = Storage::disk('s3')->put($path, $image);
    Storage::cloud()->url($path);
    // Trying to save the image to databse
    $image = new Image(['url' => $url]);
    $store->image()->save($image); // => Error
}

我在这里遵循示例,但它不起作用

这是错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'imageable_type' in 'field list' (SQL: insert into `images` (`url`, `imageable_type`, `imageable_id`, `updated_at`, `created_at`) values (images/stores/1/1551316187.jpg/Rw7BQvSeIHvNX3ldFc0GUufmcFEIAi6TiITteDyr.jpeg, AppStore, 1, 2019-02-28 01:09:49, 2019-02-28 01:09:49))

说我的"图像"表中没有列'Imagable_type'实际上在表中

任何指针都将不胜感激。

//已解决

我将图像迁移到:

public function up()
{
    Schema::create('images', function (Blueprint $table) {
        $table->increments('id');
        $table->string('url');
        $table->morphs('imageable');
        $table->timestamps();
    });
}

将" Imagable_type"列放在列" Imagable_id"之前,现在起作用。

这是因为您的迁移中有一个white space

Schema::create('images', function (Blueprint $table) {
    $table->increments('id');
    $table->string('url');
    $table->integer('imageable_id');
    $table->string(' imageable_type'); <---should be $table->string('imageable_type')
    $table->timestamps();
});

最新更新