[英]Laravel reverse query data from child to get parent
I have 2 table called defects
and defect_types
and defect_types
is the child of defects
我有 2 个表称为defects
和defect_types
,缺陷defect_types
是defects
的孩子
Now I wanted to query the defect_types
by project_id
but project_id
is not in defect_types
instead is in defect_types
parent which is defects
.现在我想通过project_id
查询defect_types
,但project_id
不在缺陷defect_types
中,而是在缺陷defect_types
父defects
中。 I couldn't get it right and below is my code:我无法正确理解,下面是我的代码:
Controller: Controller:
class ProjectDashboardController extends Controller
{
public function ajaxGetDefectTypes($proj_id)
{
$defectTypes = DefectType::with('defect')
->whereHas('defects', function ($query) {$query->where('project_id', $proj_id);})
->get();
return $defectTypes;
}
}
Model: Model:
class DefectType extends Model
{
use SoftDeletes;
protected $fillable = ['title','details','created_by','is_custom','developer_id'];
public function defects()
{
return $this->belongsToMany('App\Defect', 'defect_type_id');
}
}
JS: JS:
getDefectTypes(function (results) {
console.log(results)
})
// SECTION: API
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function getDefectTypes(onSuccess) {
var getDefectTypesRoute = "{{ route('dev-admin.projects.dashboard.defect-types.ajax.get', ['proj_id' => $proj_id ]) }}";
$.ajax({
url: getDefectTypesRoute,
type: 'GET',
data: data = {
_token: '{{ csrf_token() }}',
},
success: function(projects) {
onSuccess(projects)
},
error: function(xhr) {
if(xhr.status == 422) {
var errors = xhr.responseJSON.errors;
console.log("Error 422: ", xhr);
}
console.log("Error: ", xhr);
}
});
}
Found the solution:找到了解决方案:
Controller: Controller:
class ProjectDashboardController extends Controller
{
public function ajaxGetDefectTypes($proj_id)
{
$defectTypes = DefectType::with('defect')
->whereHas('defects', function ($query) use ($proj_id){
$query->where('project_id', $proj_id);
})
->get();
return $defectTypes;
}
}
Model: Model:
class DefectType extends Model
{
use SoftDeletes;
protected $fillable = ['title','details','created_by','is_custom','developer_id'];
public function defects()
{
return $this->hasMany('App\Defect');
}
}
JS: JS:
getDefectTypes(function (results) {
console.log(results)
})
// SECTION: API
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function getDefectTypes(onSuccess) {
var getDefectTypesRoute = "{{ route('dev-admin.projects.dashboard.defect-types.ajax.get', ['proj_id' => $proj_id ]) }}";
$.ajax({
url: getDefectTypesRoute,
type: 'GET',
data: data = {
_token: '{{ csrf_token() }}',
},
success: function(projects) {
onSuccess(projects)
},
error: function(xhr) {
if(xhr.status == 422) {
var errors = xhr.responseJSON.errors;
console.log("Error 422: ", xhr);
}
console.log("Error: ", xhr);
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.