laravel - 为什么相关的 Answer 模型没有得到 project_id?
问题描述
我有下一个模型:
Project <(Many to Many)> Experiment (One to Many)> Question (One to Many)> Answer
当我尝试Project::with('experiments.questions.answers')->find(1)
结果,我answers
不仅从project
with得到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)
但是我怎样才能将它从代码中删除并使其成为全球性的呢?
解决方案
我不明白为什么这个选择会触及其他项目,但是,如果你想创建一个方便的快捷方式来获取具有关系的项目 - 在模型或存储库中创建一个方法:
public function findWithExperiments($id) {
$project = Project::find($id);
$project->load(['experiments.questions.answers' => function ($query) use ($id) {
$query->where('project_id', $id);
}]);
return $project;
}
推荐阅读
- python - 关于 BraTS 数据集的说明
- javascript - 如何将数组插入到数组内的对象中?对于 ng2-charts / Charts.js
- json - 来自 API 的 Open.json 文件
- javascript - 识别 Javascript 中的函数名称或属性
- c - 为什么 OpenCL 中不同的本地大小会产生不同的结果?
- javascript - 使用 R2D3 时无法识别的功能
- c - C中合并排序中的代码无法正常工作
- c++ - 在 docker compose 文件中为每个服务打开一个 shell 选项卡
- python - Docker Flask Conda - 不是 conda 环境
- javascript - 删除为空或 null 的项目 - JS - MYSQL - PHP