@marcoplus For correct data retrieval, you need change the modelcode relationship to use hasOne rather than belongsTo.
- When the current (parent) model owns a related record in the child model,
hasOneis suitable. belongsTois used when the relationship's child is the current model, which isn't the case in this instance.
public function modelcode() {
return $this->hasOne(ChildModel::class, 'codeId', 'code_id');
}
Eagerly Loading Data Fetching:
$data = ParentModel::with('modelcode')->get();
This guarantees that all parent records are obtained and, if applicable, associated child data is loaded.
Setup of DataTable Column:
If there is no corresponding child record,
->addColumn('codeId', function ($query) {
return optional($query->modelcode)->codeId ?? 'N/A'; // Returns 'N/A'.
})
- When the associated child record is
null, problems are avoided by usingoptional(). 'N/A'will appear in the DataTable field if there are no child records linked to the parent.