【问题标题】:Issue with Laravel orderbyLaravel orderby 的问题
【发布时间】:2017-08-16 12:42:26
【问题描述】:

一旦客户在产品页面内单击 order by,我就会尝试按价格订购我的产品。我不断收到下一个错误: Undefined index: title (View: C:\xampp\htdocs\eshop\resources\views\content\item.blade.php) 。 我的“item.blade.php”是在单独页面中显示较大尺寸产品的页面。我认为问题出在我的控制器 Item 函数或我的模型 getItem 函数中,我可能是错的......如果你能帮助我,将不胜感激。谢谢

我的路线:

Route::get('shop/{category_url}/sorting-{sort?}', 'ShopController@products'); 

我对 content.products 的看法:

 @if($products)   

   <br><br> 
   <a href="  {{ url('shop/'.$category['url'].'/sorting-asc')}}" style="color:black"> High to low</a> |
  <a href="  {{ url('shop/'.$category['url'].'/sorting-desc')}}" style="color:black">Low to high</a>  

我的 item.blade.php:

@extends ('master') 

@section('content') 
<div class="row"> 
    <div class="col-md-12 text-center"> 
    @if('item') 
    <h1>{{ $item['title']}}</h1>  
    <p><img width="500" src="{{ asset ('images/' . $item['image'])}}" </p>  
    <p>{!! $item['article'] !!}</p>
    <p><b>Price on site:</b>{{ $item['price']}}$</p> 
    <p>  
        @if(Cart::get($item['id']))  
        <input disabled="disabled" type="button" value="In Cart!" class="btn btn-success">
        @else 
        <input data-id="{{ $item['id']}}" type="button" value="+ Add to cart" class="btn btn-success add-to-cart"> 
        @endif

        <a href="{{ url('shop/checkout') }}" class="btn btn-primary">Checkout</a> 
    </p>
        @else 
        <p class="text-center" style="font-size: 18px">No product details ...</p>  
    @endif 
    </p>
@endsection

我的控制器:

public function products(Request $request, $category_url, $sort= 'ASC'){
   Product::getProducts($category_url, self:: $data);
    $catsort = Categorie::where('url', '=', $category_url)->first();
    $products = Product::where('categorie_id', $catsort->id)->orderBy('price', $sort)->get(); 
    return view('content.products', self::$data ,['products' => $products, 'sort' => $sort]); 
}  

 public function item($category_url, $product_url){ 

       Product::getItem($product_url, self::$data);   

       return view('content.item', self::$data);
   }  

我的模特:

static public function getProducts($category_url, &$data){

    $data['products']=$data['category']=[];


    if ($category=Categorie::where('url','=', $category_url)->first()){

        $category= $category->toArray();
        $data['category']=$category;
        $data['title']=$data['title']. ' | ' . $category['title'];


        if ($products=Categorie::find( $category['id'])->products){

            $data['products']= $products->toArray();
        }
    }
}

static public function getItem($product_url, &$data) {


    $data['item'] = [];

    if ($product = Product::where('url', '=', $product_url)->first()) {

        $product = $product->toArray(); 

        $data['item'] = $product;
        $data['title'] .= '|' . $product['title'];  

    }
}

【问题讨论】:

  • 评论不适用于扩展讨论或调试会话;这个对话是moved to chat。如果您被要求澄清或评论中的一些代码,您需要在您的问题中edit它。

标签: php laravel laravel-5 laravel-5.2


【解决方案1】:

因此,根据聊天记录,我将尝试提供答案。

首先,我们需要了解您希望如何构建数据库。

我可以确定您有产品和类别。我仍然不清楚你想用 $items 实现什么。

所以,从这个开始,你有两张桌子。让我们考虑一下,以确定他们之间的关系。首先,问一个问题,一个产品可以有多少个类别(1 个或超过 1 个)?大多数人构建类别,因此产品可以有多个,所以在 Laravel 中,这被称为 HasMany 关系。与此相反的是“一个类别可以有多少产品?”。在这种情况下,答案再次大于 1。因此,这实际上是 BelongsToMany 关系,而不是 HasMany 关系。一个品类可以有很多产品,一个产品可以有很多品类。

接下来,您需要创建一个数据透视表。这是一个将存储产品 ID 和具有关系的类别 ID 的表。您可能会创建一些看起来像这样的迁移。他们每个人都应该在“up”方法中进入它自己的迁移文件。

Schema::create('products', function (Blueprint $table) {
     $table->increments('id');
     $table->string('name');
     $table->string('slug', 100)->index();
     $table->integer('price');
     $table->timestamps();
 });


Schema::create('categories', function (Blueprint $table) {
         $table->increments('id');
         $table->string('name');
         $table->string('slug', 100)->index();
         $table->timestamps();
     });


Schema::create('category_product', function (Blueprint $table) {
         $table->increments('id');
         $table->integer('category_id')->index();
         $table->integer('product_id')->index();
         $table->timestamps();
     });

接下来我们需要设置模型以接受关系。因此,在您的 Product.php 类中,添加以下方法。

public function categories(){
    return $this->belongsToMany(Category::class);
}

Category.php 类中与此相反。

public function products(){
    return $this->belongsToMany(Product::class);
}

现在,您应该可以像这样访问您的关系了

$category = Category::first();
$products = $category->products;

好的,现在让我们开始工作吧。您的路线看起来不错,尽管我不会按照您的方式添加排序。您可以像这样http://example.com/shop/test-category?sort=ASC

将其作为 GET 数据发送
Route::get('shop/{category_url}', 'ShopController@products');

好的,现在你的控制器。

public function products(Request $request, $category_url){
    $category = Category::with(['products' => function($q){
        $q->orderBy('price', request()->get('sort')??"ASC");
    }])->whereSlug($category_url)->first(); // Eager load in products

    return view('content.products', ['category' => $category]); 
} 

最后,在刀片中,您现在可以使用对象语法而不是数组语法。

@section('content') 
    Category Name: {{$category->name}} <br />
    @foreach($category->products as $product)
        Product Name: {{$product->name}} <br />
        Product Price: {{$product->price}} <br />
        Product Name: {{$product->name}} <br />
    @endforeach
@endsection

没有看到更多,我不能更具体,因为我不清楚你是如何尝试处理你的 $items 的。您应该以与我们设置产品和类别相同的方式进行设置。考虑关系并确定它是“HasMany”、“HasOne”还是“BelongsToMany”。

此外,您应该尝试遵循默认命名约定。您的数据库表应该是小写和复数。所以表名应该是“产品”和“类别”。你的模型应该是单数的。 “产品分类”。无需将其命名为“类别”。然后,对于所有数据透视表,您希望将它们命名为以下“category_product”。如此单数和字母顺序与您正在旋转的两个表。最后,在您的数据库中,您需要确保您的数据透视表列被命名为“product_id”和“category_id”,因此数据库名称的单数版本 +“_id”。

我希望这足以让你继续前进。

【讨论】:

  • 我更新了我的问题和我的代码,提供了有关“项目”目的的更多信息并添加了一些代码。请看一看。
  • 什么意思,商品是商品的大号?
  • 在您的 getItems 方法中,将 "$data['title'] .=" 更改为 "$data['title'] =".
猜你喜欢
  • 1970-01-01
  • 2014-09-05
  • 1970-01-01
  • 1970-01-01
  • 2017-02-04
  • 2017-09-07
  • 2011-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多