【发布时间】:2021-11-04 10:23:19
【问题描述】:
我想从与最后一个孩子的 where 子句的嵌套关系中获取数据(作为 json 嵌套响应)。我正在制作一个包含 4 个嵌套模型的 API,这些模型有很多这样的关系: 模型A->hasmany模型B->hasmany模型C->hasmany模型D (modelA 是第一个父级等)
我在 api.php 上有一个路由
Route::get('/rdata/{string}', [ModelAController::class, 'getdata']);
在我的 ModelAController 上:
public function getdata($string)
{
return ModelA::thedata($string);
}
然后在我的 ModelA 上
public static function thedata($string)
{
return ...
}
我想根据第 4 个 ModelD 的字段获取数据。我怎样才能对第四个孩子做一个 where 子句可能是这样的:
where('column', 'like', '%'.$string.'%')
我也尝试使用集合资源,我可以很好地嵌套所有数据,但我无法对最后一个孩子执行我想要的查询。我取得的最好成绩是对最后一个子负载父母进行查询,但它不能正常工作
return ModelD::where('column', 'like', '%'.$string.'%')->with('modelc.modelb.modela')->get();
甚至有负载
return ModelD::where('column', 'like', '%'.$string.'%')->get()->load('modelc.modelb.modela');
然后在 ModelC 上:
public function modelb()
{
return $this->belongsTo(ModelB::class, 'f_key','f_key');
}
对于其他父母也是如此,但这是错误的,因为我再次将所有孩子都放入其中,而且 json 也是反转的。我想保留格式:
$response = ['ModelA' => [
'id' => '..'
'field1' => '..'
'ModelB'=>[
etc..
]]
或者还有其他我看不到的方法吗?在某种程度上,我需要这样的东西,但在嵌套的 json 中格式化
return DB::table('modela')
->join('modelb', 'modela.id', 'modelb.modela_id')
->join('modelc', 'modelb.id', 'modelc.modelb_id')
->join('modeld', 'modelc.id', 'modeld.modeld_id')
->where('column', 'like', '%'.$string.'%')
->get();
Edit1:到目前为止,我根据答案得到了这个,我想获得最后一个孩子的父列
return self::with('modelb.modelc.modeld')-> whereHas('modelb.modelc.modeld', function ($modeld) use ($string) {
$modeld->where('column', 'like', "%$string%");
->whereColumn('modelc.column2', 'modeld.column2')
->whereColumn('modelc.column3', 'modeld.column3');
})
->with(['modelb.modelc.modeld' => function ($modeld) use ($string) {
$modeld->where('column', 'like', "%$string%");
->whereColumn('modelc.column2', 'modeld.column2')
->whereColumn('modelc.column3', 'modeld.column3');
}])
->get();
【问题讨论】: