【问题标题】:Laravel 5: Check if a category collection has a valid result or no records at allLaravel 5:检查类别集合是否有有效结果或根本没有记录
【发布时间】:2018-09-22 19:10:08
【问题描述】:

多级数据库表和 eloquent 系统的一个非常随意的问题。

一个 MainCategory 有多个 Category(categories table)

一个类别有多个产品(products table)

现在 routes.php 有:

Route::get('/categories/{slug}', ['as' => 'categories.list', 'uses' => 'ListController@getCategories'])->where('slug', '[\w\d\-\_]+');

ListController@getCategories 方法想要列出所有 products 以及 categories@987654327 下@

class ListController extends Controller
{
    public function getCategories($slug) {
        $categories = Category::orderBy('id', 'asc')
            ->select('categories.id as cat_id', 'categories.name as cat_name','categories.slug as cat_slug','products.*')
            ->join('main_categories', 'main_categories.id', '=', 'categories.main_category_id')
            ->join('products', 'products.category_id', '=', 'categories.id')
            ->where('main_categories.slug', '=', $slug)
            ->get();
        if(count($categories) >  0) {
            return view('pages.categories')->withCategories($categories);
        }
        else { // either main_categories.name not in $slug or there is no category available for this main_category

        }
    }
}

代码按预期工作正常,列出来自同一个集合对象的产品和类别。

现在有一个 else 案例。如何检查结果集合,以便区分给定 $slug 的名称中是否有 main_category 下是否没有 categories main_category$slug

查看代码,count($categories) 在这两种情况下都返回0。我不坚持我雄辩的方式。您可能会建议我使用 PHP 进行另一个查询或条件检查。 我会很感激任何可以帮助我防止这种情况进一​​步复杂化的东西。

[PS:所有关系都是直接且非常基本的(belongsTohasMany),并且表名是通用标准 - Laravel 5 的做法(使用 v5.2)。如果我的问题中需要/缺少一行代码,我想你会得到。如果您还需要什么,请随时询问。]

【问题讨论】:

    标签: php laravel laravel-5 eloquent relationship


    【解决方案1】:

    只有在 main_categories.slug 中找到 $slug 时,您的查询才会给出结果,否则它不会给出任何结果。

    【讨论】:

    • 为什么不应该有人在一个对象上调用count?这是完全有效的
    • 不,if() 条件始终为真! @abhishek
    • @eazysam 您是否尝试打印结果,您是否从查询中获得任何结果。
    • Collection {#279 ▼ #items: [] }
    • 是的,所以您不会从查询中得到任何结果。你能说一下这个蛞蝓是什么吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多