我需要按关系langs()对文件夹($ data [' contents'])进行排序,其中lang_id == 1我该怎么做?感谢。
在模型文件夹中:
class Folder extends Model
{
protected $fillable = ['active', 'date', 'path', 'slug'];
public function langs()
{
return $this->hasMany('App\Models\LangFolder');
}
}
在模型LangFolder中:
class LangFolder extends Model
{
protected $fillable = ['folder_id', 'lang_id', 'name', 'description'];
public function folder()
{
return $this->belongsTo('App\Models\Folder');
}
}
在控制器中:
public function folders()
{
// Sort folders ($data['contents']) by relationship langs() where lang_id == 1
$data['folders'] = Folder::all();
$data['langs'] = Lang::all();
$directory = 'library/';
$elements = array_diff(scandir($directory), array('..', '.'));
foreach($elements as $element) {
if (is_dir($directory . '/' . $element)) {
$content_element = Folder::where('slug', $element)->first();
$data['contents'][] = $content_element;
}
}
return view('web.library.index', compact('data'));
}
答案 0 :(得分:0)
如果您想从关系中订购,则必须使用Collection
代替Eloquent
,例如:
$orderedLangs = $folder->langs->sortBy('lang_id');
答案 1 :(得分:0)
我最后在数组中添加了关系字段“name”,并且我已将数组转换为集合,然后,我按“name”排序不区分大小写。也许还有另一种清洁解决方案。这有效:
控制器:
foreach($elements as $element){
if(is_dir($directory.'/'.$element)){
$content_element = Folder::where('slug', $element)->first();
$contenidos[] = $content_element;
}else{
$data['documents'][] = Document::where('path', $directory.'/'.$element)->first();
}
}
foreach($contenidos as $contenido){
foreach($contenido->langs as $lang){
if($lang->lang_id == '1'){
$contenido->name = $lang->name;
}
}
$data['contents'][]= $contenido;
}
$data['contents']=collect($data['contents'])->sortBy('name', SORT_NATURAL|SORT_FLAG_CASE);