简体   繁体   English

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

[英]Laravel - Arranging images in ascending and descending order with links

I have a create method in my controller 我的控制器中有一个create方法

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]);
}

This is my blade view 这是我的刀片视图

<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

Question- How can i make the asc button sort the images in ascending order and des in descending order, is there a way to connect it to my controller, or is there a way to sort them in ascending and descending order through <a href> links? 问题-如何使asc按钮将图像按升序排序,将des按降序排序,是否可以将其连接到控制器,或者是否可以通过<a href>按升序和降序对它们进行排序链接?

First, foreach overrides $id in each iteration, so finally value of $id is $property_id value of last item from $image array. 首先, foreach在每次迭代中都覆盖$id ,因此$id最终值是$image数组中最后一项的$property_id值。

You need to define relations. 您需要定义关系。

In PropertyUser class add: PropertyUser类中添加:

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

Then, in your create method in controller: 然后,在控制器的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]);
}

Your link to sorted images should like: <a href="/create.html?direction=asc">Sort asc</a> 您指向已排序图像的链接应为: <a href="/create.html?direction=asc">Sort asc</a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM