【发布时间】:2020-10-24 22:09:00
【问题描述】:
我在 Laravel 7.24 上,现在我有一个 blogs 表、模型和控制器。我正在拨打/slug 的电话,并尝试使用mutator 和雄辩的create() 将博客文章保存为测试。奇怪的是,我的 mutator 将 slug 保存到 DB,但 DB 中的标题单元格保存为空字符串。如果我让 mutator 为标题工作,那么它会保存标题,但 slug 会保存为空字符串。为什么它只保存一个或另一个?
博客迁移:
public function up()
{
Schema::create('blogs', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('post');
$table->string('postExcerpt');
$table->string('slug')->unique();
$table->string('user_id');
$table->string('featuredImage');
$table->string('metaDescription');
$table->integer('views')->default(0);
$table->timestamps();
});
}
控制器方法
public function slug()
{
return Blog::create([
'title' => 'This is a nice title',
'post' => 'some post',
'postExcerpt' => 'some post here',
'user_id' => 11,
'metaDescription' => 'some meta info here',
]);
}
博客模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Blog extends Model
{
protected $fillable = [
'title',
'post',
'postExcerpt',
'slug',
'user_id',
'featuredImage',
'metaDescription',
'views'
];
public function setSlugAttribute($title){
$this->attributes['slug'] = $this->uniqueSlug($title);
}
private function uniqueSlug($title)
{
$slug = Str::slug($title, '-');
$count = Blog::where('slug', 'LIKE', "{$slug}%")->count();
$newCount = $count > 0 ? ++$count : '';
return $newCount > 0 ? "$slug-$newCount" : $slug;
}
}
更新:我将表恢复为原始迁移,但所有其他代码都是相同的。
这是我得到的错误
SQLSTATE[HY000]: General error: 1364 Field 'slug' doesn't have a default value (SQL: insert into `blogs` (`title`, `post`, `postExcerpt`, `user_id`, `metaDescription`, `updated_at`, `created_at`) values (This is a nice title, some post, some post here, 11, some meta info here, 2020-10-24 22:28:07, 2020-10-24 22:28:07))
【问题讨论】:
-
正确的 uniqueSlug 方法,不起作用
-
您没有发送任何数据供 mutator 使用。你需要做类似
'slug' => $post->title