使用 laravel v9 和 Filament v2 对于我的多对多关系 书籍和类别
这是错误
SQLSTATE[HY000]: General error: 1364 Field 'category_id' doesn't have a default value
INSERT INTO
`books` (
`image`,
`title`,
`author_id`,
`publication_date`,
`copies`,
`updated_at`,
`created_at`
)
VALUES
(
Uqvz9qyKeqt11XmrlntLZuWWkgKYjT - metaNDAzNjI1ODg3XzE4MDU4MDc2MTY1MzUyNjdfOTIxNjYxODQ2MjE5MTc5ODE1OV9uLmpwZw = = -.jpg,
AS,
1,
AS,
AS,
2023 -12 -13 16: 14: 00,
2023 -12 -13 16: 14: 00
)
“as”是我测试它的输入
我的填写表格
public static function form(Form $form): Form
{
return $form
->schema([
Card::make()
->schema([
FileUpload::make('image')->image(),
TextInput::make('title')
->required()
->maxLength(255),
select::make('author_id')
->relationship('author', 'full_name')
->required(),
Select::make('category_id')
->multiple()
->relationship('categories', 'name')
->preload()
->required(),
TextInput::make('publication_date')
->required()
->maxLength(255),
TextInput::make('copies')
->required()
->maxLength(255)
])
]);
}
对于我的模型
class Book extends Model
{
use HasFactory;
protected $fillable = ['author_id','image','category_id','title','language','publication_date','copies'];
protected $casts = [
'category_id' => 'array',
];
public function author(){
return $this->belongsTo(Author::class);
}
public function categories(){
return $this->belongsToMany(Category::class);
}
} `
`class Category extends Model
{
use HasFactory;
protected $fillable = ['name'];
public function books(){
return $this->hasMany(Book::class);
}
}
为了我的迁移
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->id();
$table->foreignId('author_id')->constrained()->cascadeOnDelete();
$table->foreignId('category_id')->constrained()->cascadeOnDelete();
$table->string('image');
$table->string('title');
$table->string('publication_date');
$table->string('copies');
$table->timestamps();
});
}
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
我尝试了很多方法,但似乎无法解决 我希望它作为数组保存到我的数据库中,因为它是多对多的关系 这样我就可以在灯丝表中显示它
根据您的桌子设计,这是行不通的。
您已添加
belongsToMany
关系。
不过,应该是这样的
模型\Book.php
class Book extends Model
{
public function category()
{
return $this->belongsTo(Category::class);
}
}
模型\Category.php
class Category extends Model
{
public function books()
{
return $this->hasMany(Book::class);
}
}
在这种情况下,您一次只能为预订分配一个类别。
如果您想为一本书分配多个类别,请创建一个数据透视表
book_category
并且在关系中您需要添加以下更改
模型\Book.php
class Book extends Model
{
public function categories()
{
return $this->belongsToMany(Category::class);
}
}
模型\Category.php
class Category extends Model
{
public function books()
{
return $this->belongsToMany(Book::class);
}
}
然后在您的选择输入中将使用此
Select::make('category_id')
->multiple()
->relationship('categories', 'name')
->preload()
->required(),
更多参考,
V2:https://filamentphp.com/docs/2.x/forms/fields#populate-automatically-from-a-relationship
V3:https://filamentphp.com/docs/3.x/forms/fields/select#integrating-with-an-eloquent-relationship