Laravel - 使用链接按升序和降序排列图像

时间:2018-05-19 06:23:21

标签: php laravel laravel-5

我的控制器中有一个创建方法

myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                     // do what you have to do
                }

            }
        });

这是我的刀片视图

public function create()
{
    $image = PropertyUser::where('user_id', '=', Auth::user()->id)->get();
    foreach($image as $property)
    {
        $id = $property->property_id;
    }
    $image_main = Image::where('property_id', $id)->get();
    return view('settings.photos', ['image_array' => $image_main]);
}

Question- 如何让asc按钮按升序排序图像,按降序排序des,有没有办法将它连接到我的控制器,或者有办法通过<form name="asc" action="{{route("settings.photos")}}" method="post" class="text-center"> @csrf <input type="submit" value="Ascending " class="settings-photos-header2 text-center"/> | </form><form name="dec" action="{{route("settings.photos")}}" method="post" class="text-center"> @csrf <input type="submit" value= " Descending" class="settings-photos-header2 text-center"/> </form> <h2 class="settings-photos-header2 text-center">Photo Gallery</h2> @foreach ($image_array as $images) <div class="image-warp"><img src="{{$images->filename}}" style="width:100px;height:100px;"><br/><span style="color: #1b1e21">{{$images->description}}</span> </form> </div> @endforeach 链接按升序和降序对它们进行排序?

1 个答案:

答案 0 :(得分:0)

首先,foreach会在每次迭代中覆盖$id,因此最终$id的值为$property_id数组中最后一项的值$image

您需要定义关系。

PropertyUser班级中添加:

public function images() {
  return $this->belongsTo(Image::class, 'property_id');
}

然后,在控制器中的create方法中:

public function create(Request $request) {    

  // use direction query parameter to define asc or desc sorting
  $order_direction = $request->query('direction');

  $property_user = PropertyUser::where('user_id', '=', Auth::user()->id)
                                 ->with(['images' => function($query) use ($order_direction) {
                                     $query->orderBy('id', $order_direction)                                     
                                 })->get();

  // here you can access an array with associated images:
  $images = $property_user->images;  

  return view('settings.photos', ['image_array' => $images]);
}

指向已排序图片的链接应为:<a href="/create.html?direction=asc">Sort asc</a>