Php Laravel Eloquent with()方法与';其中';但是';t与';模型::find()';
我想使用Laravel EloquentPhp Laravel Eloquent with()方法与';其中';但是';t与';模型::find()';,php,laravel,orm,eloquent,Php,Laravel,Orm,Eloquent,我想使用Laravel Eloquentwith()建立3个表之间的关系。 这是我的代码(关系在模型中设置): 但此代码返回所有请求表单,只返回id=7 这是输出: Collection {#895 ▼ #items: array:4 [▼ 0 => RequestForm {#796 ▶} 1 => RequestForm {#797 ▶} 2 => RequestForm {#798 ▶} 3 => RequestForm {#79
with()
建立3个表之间的关系。
这是我的代码(关系在模型中设置):
但此代码返回所有请求表单
,只返回id=7
这是输出:
Collection {#895 ▼
#items: array:4 [▼
0 => RequestForm {#796 ▶}
1 => RequestForm {#797 ▶}
2 => RequestForm {#798 ▶}
3 => RequestForm {#799 ▶}
]
}
当我将->get()
替换为->first()
时,它只返回请求表单
,但它的id是1:(
但这段代码非常有效:
$request_form = RequestForm::where('id', 7)->with(['RequestFormsCheck' => function ($q) {
$q->orderBy("created_at", "DESC")->with('RequestFormsCheckOptions');
}])->first();
dd($request_form->toArray());
这是它的输出(这是我期望得到的):
以下是我的迁移:
Schema::create('request_forms', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 100)->nullable();
$table->string('email', 100)->nullable();
$table->string('telephone', 20)->nullable();
$table->text('description')->nullable();
$table->string('site', 100);
$table->integer('item_id');
$table->string('lang');
$table->timestamps();
});
及
还有这个
Schema::create('request_forms_checks', function (Blueprint $table) {
$table->increments('id');
$table->integer('request_form_id')->unsigned();
$table->foreign('request_form_id')->references('id')->on('request_forms')->onDelete('cascade');
$table->tinyInteger('type')->comment("1: option, 2:description");
$table->integer('request_forms_check_options_id')->unsigned()->nullable();
$table->foreign('request_forms_check_options_id')->references('id')->on('request_forms_check_options')->onDelete('cascade');
$table->text('description')->nullable();
$table->timestamps();
});
首先,我会向您介绍,但为了记录在案,我会再次解释,因为我理解:
当您使用find()
方法时,已经返回了模型的一个实例(这不是查询生成器),这就是为什么对find的结果使用with()
将对数据库执行新的查询,然后调用get()
将返回整个记录,而调用first()
将返回第一条记录(凭身份证)
如果您仍然想坚持使用find()
- 让
find()
$request_form = RequestForm::with(['RequestFormsCheck' => function ($q) {
$q->orderBy("created_at", "DESC")->with('RequestFormsCheckOptions');
}])->find(7);
$request_form = RequestForm::find(7)->load(['RequestFormsCheck' => function ($q) {
$q->orderBy("created_at", "DESC")->with('RequestFormsCheckOptions');
}]);
- 使用
load()
find(Lazy-loaded)之后-您得到结果,然后加载相关模型。示例:
$request_form = RequestForm::with(['RequestFormsCheck' => function ($q) {
$q->orderBy("created_at", "DESC")->with('RequestFormsCheckOptions');
}])->find(7);
$request_form = RequestForm::find(7)->load(['RequestFormsCheck' => function ($q) {
$q->orderBy("created_at", "DESC")->with('RequestFormsCheckOptions');
}]);
- 在调用最终结果之前,请坚持使用()调用整个查询。我认为这是最好的方法,因为您只需要一个RequestForm,然后多个关系
我对with()
工作原理的一般理解是在查询生成器上,因此您必须在with()
相关之前将查询集合起来(这个想法可能需要更新)
您可能需要阅读更多关于
$request_form = RequestForm::find(7)->load(['RequestFormsCheck' => function ($q) {
$q->orderBy("created_at", "DESC")->with('RequestFormsCheckOptions');
}]);