Laravel 5.5 BelongsToMany returns 空

Laravel 5.5 BelongsToMany returns empty

我正在尝试使用 belongsToMany 关系,我从来没有遇到过任何问题,但由于某种原因,它 return 是空的。

我在 Store 模型中设置了这样的关系:

    public function images()
    {
        return $this->belongsToMany('App\Images', 'images_stores', 'image_id', 'store_id');
    }

当我测试关系时,return没有错误只是一个空集合,尽管它不是。这是我访问数据的方式:

    public function edit($id)
    {
        $store = Store::find($id);
        dd($store->images);

        return view('admin.pages.store.edit', compact('store'));
    }

但它只是 return 一个空集合,我希望有人能帮我解决这个问题。这些是我的迁移文件,但我认为问题不在迁移文件中。

    Schema::create('images', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('path');
        $table->timestamps();
    });
    // pivot table
    Schema::create('images_stores', function (Blueprint $table) {
        $table->increments('id');

        $table->integer('image_id')->unsigned()->nullable();
        $table->foreign('image_id')->references('id')->on('images')->onDelete('cascade');

        $table->integer('store_id')->unsigned()->nullable();
        $table->foreign('store_id')->references('id')->on('stores')->onDelete('cascade');

        $table->timestamps();
    });
    // store table
    Schema::create('stores', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('location');
        $table->string('email');
        $table->timestamps();
    });

谢谢大家。

我认为 id 是颠倒的。试试这个:

public function images()
{
    return $this->belongsToMany('App\Images', 'images_stores', 'store_id', 'image_id');
}