卡在数据库查询中,laravel

时间:2018-10-29 22:42:25

标签: php database laravel

我需要你的帮助... 无法找出问题所在。 我试图显示一个子类别的所有产品。有时它显示第一个或最后一个记录。然后它重复同一记录多次(与循环相同)。

category: id, name, visible

products:id, name, 

category_products:id, id_product, id_category

Route::get('navigation/{id}',function($id){
  $prods= \App\Products_to_Categories::where('id_category',$id)->get();
     $products=array();

    foreach ($prods as $prod)
    {
       $products[] = \App\Products::find($prod->id_product)->
                      where('visible','yes')
                     -> where('delete','no')->first();

    }


    return view('subcategories.order_products',
        ['products'=>$products ]);}

查看刀片

<div class="col-md-6 col-md-offset-1">
                            <ul id="sortable">
                                @foreach($products as $product)
                                    <li class="ui-state-default" id="{{ $product->id}}"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span> {{$product->name}}</li>
                                @endforeach
                            </ul>

                        </div>

2 个答案:

答案 0 :(得分:0)

在Laravel中尝试> = 5.2::

 $prods= \App\Products_to_Categories::where('id_category',$id)->get();
 $products=array();
 $whereIn = array();

 foreach ($prods as $prod)
 {
     $whereIn[] = $prod->id_product;
 }

 $products[] = \App\Products::find($prod->id_product)
                ->where('visible','yes')
                -> where('delete','no')
                ->whereIn('id', $whereIn)
                ->orderByRaw('RAND()')
                ->get();

这将为您提供随机排序的特定类别的产品列表。

Laravel 4.2.7-5.1:

User::orderByRaw("RAND()")->get();

Laravel 4.0-4.2.6:

User::orderBy(DB::raw('RAND()'))->get();

Laravel 3:

User::order_by(DB::raw('RAND()'))->get();

来源: Laravel - Eloquent or Fluent random row

答案 1 :(得分:0)

产品和类别似乎通过联接表category_products相关联,因此您可以设置belongsToMany()关系并从CategoryProduct进行查询,而无需遍历联接表。< / p>

https://laravel.com/docs/5.7/eloquent-relationships#many-to-many

类别模型:

public function products()
{
    return $this->belongsToMany(\App\Products::class, 'category_products', 'id_category', 'id_product');
}

产品型号:

public function categories()
{
    return $this->belongsToMany(\App\Category::class, 'category_products', 'id_product', 'id_category');
}

控制器代码:

$category = Category::find($id);
$products = $category->products()
                     ->where('visible', 'yes')
                     ->where('delete', 'no')
                     // ->inRandomOrder()   // un-comment this if you want results in random order
                     ->get();