【问题标题】:Many to Many Eloquent - Same Model多对多 Eloquent - 同一模型
【发布时间】:2016-08-30 23:47:03
【问题描述】:

对不起,我是一个相对的 Laravel 初学者。

我有一个名为 PACS 的模型。每个 PACS 都可以与许多其他 PACS 相关联。人与人之间的关系也有方向,推或拉。

我的 PACS 模型定义为多对多关系

public function pacsRelation() {
        return $this->belongsToMany('App\PACS', 'pacs_has_pacs', 'pacsId', 'hasPacsId')->withTimestamps()->withPivot('transferRelation');
    }

我的数据透视表是

Schema::create('pacs_has_pacs', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
            $table->integer('pacsId')->unsigned();
            $table->integer('hasPacsId')->unsigned();
            $table->enum('transferRelation', ['push', 'pull']);

            $table->foreign('pacsId')->references('pacsId')->on('pacs');
            $table->foreign('hasPacsId')->references('pacsId')->on('pacs');
        });

我的 PACS 模型表是

Schema::create('pacs', function (Blueprint $table) {
            $table->increments('pacsId');
            $table->timestamps();
            $table->string('email');
            $table->string('name');
            $table->string('fax')->nullable();
            $table->string('edi')->nullable();
            $table->string('contact');
        });

我在执行以下代码时遇到问题,并且我的数据透视表中没有出现任何行且没有错误。

public function handle()
    {

        $this->error("The relationship is defined push or pull by how the receiving party is able to retreive images from the sending party.");

        $valid = false;

        while (!$valid) {

            $receiving = $this->ask('Receiving PACS name');

            try {
                $pacs = PACS::where('name', '=', $receiving)->firstOrFail();
            } catch (ModelNotFoundException $e) {
                $this->error('This PACS does not exist');
                continue;
            }

            $valid = true;

        }

        $this->info($pacs);

        $valid = false;

        while (!$valid) {

            $sending = $this->ask('Sending PACS name');

            try {
                $sendingPacs = PACS::where('name', '=', $sending)->firstOrFail();
            } catch (ModelNotFoundException $e) {
                $this->error('This PACS does not exist');
                continue;
            }

            $valid = true;

        }

        $this->info($sendingPacs);

        $relation = $this->choice('Push or Pull relation?', ['push', 'pull']);

        $pacs->pacsRelation()->save($sendingPacs, ['transferRelation'=>$relation]);

        $this->info('Relationship successfully defined.');

    }

有什么明显的我遗漏了,还是我做错了?

【问题讨论】:

标签: php laravel eloquent many-to-many


【解决方案1】:

经过数小时的查看后,这个问题的解决方案归结为 Laravel 无法识别我的表的主键。

我必须定义

protected $primaryKey = 'pacsId';

在我的 PACS 模型上,我不在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多