【问题标题】:Laravel 5.5 BelongsToMany returns emptyLaravel 5.5 BelongsToMany 返回空
【发布时间】:2017-12-09 01:46:04
【问题描述】:

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

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

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

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

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

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

但它只会返回一个空集合,我希望有人可以帮助我解决这个问题。这些是我的迁移文件,但我认为问题不在迁移文件内部。

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

谢谢大家。

【问题讨论】:

    标签: php laravel laravel-5 eloquent laravel-5.5


    【解决方案1】:

    我认为ids 是倒置的。试试这个:

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

    【讨论】:

    • 那太愚蠢了。当我自己尝试时,它会返回一个错误,但它确实有效,非常感谢!
    猜你喜欢
    • 2014-11-23
    • 1970-01-01
    • 2017-06-04
    • 2019-05-31
    • 2017-01-28
    • 2019-04-29
    • 2020-02-02
    • 2018-04-21
    • 2020-06-03
    相关资源
    最近更新 更多