Laravel多对多的多态关系并不起作用

时间:2016-09-18 05:42:35

标签: php laravel polymorphism many-to-many

嗨我试图使用多对多的多态,但不知何故它不起作用我附上我的代码你能找出我做错了吗?

我的迁移:

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

1 个答案:

答案 0 :(得分:2)

以下是您应该如何定义关系:

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

Sticker

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

Stickable

你不需要你的关系模型(Stickable)。你应该为贴纸创建一个模型并定义你的关系。

Trip可以参考stickable或与贴纸建立关系所需的任何其他类型的模型。但是,在您的代码中,Trip模型上有enum Scope{AE, FJ, //... static Scope inScope(String s){ return Arrays.asStream(Scope.values()) .stream().filter(s -> isInScope(s)).findFirst().get(); } abstract boolean isInScope(String word); } Function<String, Scope> f = Scope::inScope; // in code listOfWords.stream().groupBy(f).values(); 方法,这是没有意义的。

Eloquent Many to Many Polymorphic Relationships