简体   繁体   English

Laravel多对多态关系不起作用

[英]Laravel Many To Many Polymorphic Relation doesn't work

hi I'm trying to use many to many polymorphic but somehow it doesnt work I attach my code can you find out what I do wrong? 您好,我尝试使用多对多态,但以某种方式不起作用,我附上了我的代码,您能找出我做错了什么吗?

my migration : 我的迁移:

 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();
    });

and my models 和我的模特

Trip model: 行程模式:

public function stickables()
{
    return $this->morphToMany(Stickable::class, 'stickable');
}

Stickable model: 粘性模型:

 public function trips()
{
    return $this->morphedByMany(Trip::class, 'stickable');
}

controller: 控制器:

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');
}

Here is how you should define your relationship: 这是定义关系的方式:

Trip Model: Trip模式:

public function stickers()
{
    return $this->morphToMany(Sticker::class, 'stickable');
}

Sticker Model: Sticker型号:

public function trips()
{
    return $this->morphedByMany(Trip::class, 'stickable');
}

You don't need a model for your relationship ( Stickable ).You should create a model for stickers and define your relationship on that. 您不需要关系模型( Stickable )。您应该为贴纸创建模型并在上面定义关系。

Stickable can refer to Trip or any other type of model you need to create a relationship with stickers. Stickable可以指的是Trip或您需要创建与贴纸的关系的任何其他类型的模型。 However in your code you have a stickable method on the Trip model, which does not make sense. 但是,在您的代码中, Trip模型上有一个stickable方法,这没有任何意义。

Eloquent Many to Many Polymorphic Relationships 雄辩的多对多态关系

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM