简体   繁体   中英

Laravel 5.5 BelongsToMany returns empty

I'm trying to use a belongsToMany relation, i never had any problems with it but for some reason it returns empty.

I've set up my relation in the Store model like this:

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

When i test the relationship it returns no error just a empty collection although it's not. This is the way i access the data:

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

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

But it would just return a empty collection, i hope someone could help me out with this. These are my migration file's but i don't think the problem is inside the migration files.

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

Thanks guys.

I think the id s are inverted. Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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