我需要在控制器中添加一个if条件。
这里是我的控制器:
public function edit($id)
{
$model = Models::with('model_media')->findOrFail($id);
$modelM = ModelMedia::get();
if($modelM->sort == ''){
$data['allMedia'] = ModelMedia::where([["model_id", "=", $id]])->orderBy('sort')->get();
}else{
$data['allMedia'] = ModelMedia::where([["model_id", "=", $id]])->orderBy('sort', 'DESC')->get();
}
所以...如果列sort
为空(null),则需要显示结果->orderBy('sort', 'DESC')
,如果列sort
不为空,则需要->orderBy('sort')
这是我在dd($ modelM)中得到的
Collection {#739 ▼
#items: array:86 [▼
0 => ModelMedia {#740 ▼
#table: "model_medias"
#fillable: array:5 [▼
0 => "model_id"
1 => "name"
2 => "type"
3 => "tag"
4 => "sort"
]
您需要empty()
功能吗? https://www.php.net/manual/en/function.empty.php
public function edit($id)
{
$model = Models::with('model_media')->findOrFail($id);
$modelM = ModelMedia::get();
if(empty($modelM->sort)){
$data['allMedia'] = ModelMedia::where([["model_id", "=", $id]])->orderBy('sort')->get();
}else{
$data['allMedia'] = ModelMedia::where([["model_id", "=", $id]])->orderBy('sort', 'DESC')->get();
}
}
如果值是以下任何一个,则Empty返回true: