【问题标题】:selecting all fields from secondary table in eloquent在 eloquent 中从辅助表中选择所有字段
【发布时间】:2017-03-11 00:25:59
【问题描述】:

我的查询没有结束有什么原因吗?,我尝试在 eloquent 的连接中从辅助表中获取所有值:

   Product::leftJoin('brands', 'products.brand_id', '=', 'brands.id')
                    ->leftJoin('product_categories', function($query) use ($parent){
                        $query->on('products.category_id', '=', 'product_categories.id')
                            ->where('product_categories.parent_id', $parent);
                    })
                    ->selectRaw('brands.*')
                    ->groupBy('brands.id') 
                    ->get();

如果我选择产品。* 查询正常,但对于品牌。* 它永远不会结束,有人知道发生了什么吗?

如果我直接在 phpmyadmin 中运行 sql,它会给我结果。

我需要这个查询是获取所有品牌的现有产品,其类别具有 parent_id = $parent

【问题讨论】:

  • 我建议在 eloquent 中使用关系而不是 SQL,因此您可以使用 Product::brands()->with('product_categories') 之类的东西。 Read the docs on relationships.
  • 感谢您的回答 Thomas,但我需要通过此查询获得 所有具有其类别具有 parent_id = $parent 的现有产品的品牌,您认为我可以吗用人际关系来做这件事吗?
  • 您可能想了解Has Many Through 关系。你需要读几遍才能理解它,但听起来它会做你需要做的事情。还可以考虑围绕 Eloquent 构建数据,它会让你的生活更轻松——也许数据库会更加规范化。

标签: php mysql laravel-eloquent


【解决方案1】:

我不知道为什么 eloquent 在从第二个表中获取字段时出现问题,但我使用了查询生成器,所以这个查询可以工作。我留下我的“解决方案”,也许它对某人有用:

    $brands = Product::leftJoin('brands', 'products.brand_id', '=', 'brands.id')
                    ->leftJoin('product_categories', function($query) use ($parent){
                        $query->on('products.category_id', '=', 'product_categories.id')
                            ->where('product_categories.parent_id', $parent);
                    })
                    ->selectRaw('brands.*')
                    ->groupBy('brands.id');
        $bindings = $brands->getBindings();
        $sql = $brands->toSql();
        $sql = vsprintf(str_replace('?', '%s', $sql), $bindings);
        $brands = \DB::select($sql);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    相关资源
    最近更新 更多