php - Laravel 获取所有具有类别的记录

标签 php laravel laravel-5.2 categories webshop

所以我已经为此苦苦挣扎了一段时间。 我不想获取所有包含特定数据透视表 category 的“产品”。

所以我有一条路线:

Route::get('products/{category}', ['as' => 'category.products', 'uses' => 'ProductsController@getCatProducts']);

还有一个产品模型:

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

然后是我的 Controller :

public function getCatProducts($categoryUrl)
{
    $products = Product::get();

    $productsWithCat = [];

    // loop through all projects
    foreach($products as $product) {

        // loop through all categories assigned to product
        $categories = $product->categories;
        foreach($categories as $category) {

            // check if product has category from url
            if ($category->title == $categoryUrl) {
                array_push($productsWithCat, $product);
            }
        }
    }

    $category = $categoryUrl;
    $products = $productsWithCat;

    return view('pages.category-products', compact('products', 'category'));
}

所以这是有效的,但可能有更好的方法来做到这一点。 像这样的东西:

$products = Product::with('categories.title', $categoryUrl)->get();

而且我的方法返回一个数组而不是一个集合,所以我什至无法访问我的 Blade 中的类别。

我希望有人能帮助我。

谢谢!

最佳答案

有一个更好的方法,而且你很接近...

$products = Product::with('categories')
    ->whereHas('categories', function($q) use ($categoryUrl) {
        $q->where('title', $categoryUrl);
    })->get();

关于php - Laravel 获取所有具有类别的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38145475/

相关文章:

php - 函数前的下划线在php中是什么意思?

phpunit - Artisan::call() 测试失败

laravel - 未找到类 'App\Http\Controllers\Session'

laravel - 覆盖 Laravel 队列监听器输出 [仅限 Laravel <=5.2]

php - Laravel 5.2 队列和作业 - 不推送到作业数据库

php - Laravel 5 : the move() function doesn't save the uploaded image file

php - 如何将sql数据导入sqlite?

javascript - 如何在通过 ajax 执行后期操作时克服 CORS 重定向问题?

javascript - 如何使按钮在单击时禁用/启用?

php - 在数据库中保存一个列表,然后显示列表。拉维