首页 > 解决方案 > 为什么相关的 Answer 模型没有得到 project_id?

问题描述

我有下一个模型:

Project <(Many to Many)> Experiment (One to Many)> Question (One to Many)> Answer

当我尝试Project::with('experiments.questions.answers')->find(1)

结果,我answers不仅从projectwith得到id: 1,而且从其他人那里得到。

结构Answer型号:

<?php

use App\Models\Answer;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAnswersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('answers', function (Blueprint $table) {
            $table->increments('id');
            $table->string('answer')->nullable();
            $table->integer('confidence_score')->unsigned()->default(0);
            $table->integer('state')->unsigned()->default(Answer::READY);
            $table->integer('element_id')->unsigned();
            $table->integer('question_id')->unsigned();
            $table->integer('project_id')->unsigned();
            $table->timestamps();

            $table->foreign('question_id')->references('id')->on('questions')->onDelete('cascade');
            $table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('answers', function ($table) {
            $table->dropForeign(['question_id']);
            $table->dropForeign(['project_id']);
        });

        Schema::drop('answers');
    }
}

如果我添加下一个条件,它是工作: Project::with(['experiments.questions.answers' => function($query) {$query->where('project_id', 1);}])->find(1)

但是我怎样才能将它从代码中删除并使其成为全球性的呢?

标签: laraveleloquent

解决方案


我不明白为什么这个选择会触及其他项目,但是,如果你想创建一个方便的快捷方式来获取具有关系的项目 - 在模型或存储库中创建一个方法:

public function findWithExperiments($id) {
    $project = Project::find($id);
    $project->load(['experiments.questions.answers' => function ($query) use ($id) {
        $query->where('project_id', $id);
    }]);

    return $project;
}

推荐阅读