lundi 18 novembre 2019

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

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. I couldn't get it right and below is my code :

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 :

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 :

getDefectTypes(function (results) {
    console.log(results)
})


// SECTION: API
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

function getDefectTypes(onSuccess) {
    var getDefectTypesRoute = "";
    $.ajax({
        url: getDefectTypesRoute,
        type: 'GET',
        data: data = {
        _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);
        }
    });
}


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire