Php Laravel多对多多态关系不';行不通
嗨,我正在尝试使用多对多多态性,但不知怎么的,它不起作用。我附加了我的代码。你能找出我做错了什么吗 我的迁移:Php Laravel多对多多态关系不';行不通,php,laravel,polymorphism,many-to-many,Php,Laravel,Polymorphism,Many To Many,嗨,我正在尝试使用多对多多态性,但不知怎么的,它不起作用。我附加了我的代码。你能找出我做错了什么吗 我的迁移: Schema::create('stickers', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('type'); $table->timestam
Schema::create('stickers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('type');
$table->timestamps();
});
Schema::create('stickables', function (Blueprint $table) {
$table->integer('sticker_id')->nullable();
$table->integer('stickable_id');
$table->string('stickable_type');
$table->primary(['sticker_id', 'stickable_id', 'stickable_type']);
$table->foreign('sticker_id')
->references('id')->on('stickers')
->onDelete('cascade');
$table->timestamps();
});
还有我的模特
出行模式:
public function stickables()
{
return $this->morphToMany(Stickable::class, 'stickable');
}
可粘贴模型:
public function trips()
{
return $this->morphedByMany(Trip::class, 'stickable');
}
控制器:
public function store(Request $request)
{
$trip = new Trip();
$trip->name = $request->name;
$trip->desc = $request->desc;
$trip->creator_id = Auth::user()->id;
$trip->save();
$tags=$request->tags;
$trip->stickables()->attach($tags);
$trip->save();
return redirect('/trip');
}
以下是您应该如何定义您的关系:
行程
型号:
public function stickers()
{
return $this->morphToMany(Sticker::class, 'stickable');
}
public function trips()
{
return $this->morphedByMany(Trip::class, 'stickable');
}
标签
型号:
public function stickers()
{
return $this->morphToMany(Sticker::class, 'stickable');
}
public function trips()
{
return $this->morphedByMany(Trip::class, 'stickable');
}
你不需要为你的关系建立一个模型(Stickable
)。你应该为贴纸创建一个模型,并在此基础上定义你的关系
Stickable
可参考Trip
或您需要与标签建立关系的任何其他类型的型号。但是,在您的代码中,在Trip
模型上有一个stickable
方法,这是没有意义的
您能否指定哪些不起作用?您期望的结果是什么,而您得到的结果是什么?@Matey确定我想做这样的事情
$trip->stickables()->get()
,但我什么也没得到,我查看了我的数据库stickables表,标签id总是null@MohammadrezA您可以尝试使用sync方法,而不是attach$trip->stickables()->sync($tags)
@Gadzhev是的,我试过了,但没用