使用Laravel Datatables包:https://github.com/yajra/laravel-datatables
我渴望加载belongsTo
关系。但是,对于某些行,关系可能不存在,relationship_id
列将为空。
这导致数据表出现问题:
{ data: 'relationship.name' },
如果关系不存在,则会抛出错误。如果未找到关系,如何为此特定列设置默认值?我尝试使用editColumn
,它用于排序,但不用于搜索。
答案 0 :(得分:2)
您可以使用withDefault()
:
public function relationship()
{
return $this->belongsTo(...)->withDefault(['name' => 'default']);
}
答案 1 :(得分:0)
作为数据表的文档
https://datatables.net/reference/option/columns.defaultContent
说你可以使用
$('#example').dataTable( {
"columns": [
null,
null,
null,
{
"data": "first_name", // can be null or undefined
"defaultContent": "<i>Not set</i>"
}
]
} );
如果条件像这样,你也可以做出另一个答案
{if (item.relationship != null) {
return item.relationship;
}
return ''; //this is the default if the relationship doesn't exist
}