我有以下型号:
Project <(Many to Many)> Experiment (One to Many)> Question (One to Many)> Answer
当我尝试Project::with('experiments.questions.answers')->find(1)
结果,我不仅从answers
和project
那里获得了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)
但是如何从代码中删除它并使它成为全局的?
答案 0 :(得分:0)
我不知道为什么这个选择会影响其他项目,但是,如果您要创建方便的快捷方式来获取具有关系的项目,请在模型或存储库中创建方法:
public function findWithExperiments($id) {
$project = Project::find($id);
$project->load(['experiments.questions.answers' => function ($query) use ($id) {
$query->where('project_id', $id);
}]);
return $project;
}
答案 1 :(得分:-1)
尝试此代码
Project::with('experiments.questions.answers')->find([1])