首页 文章

如何在laravel中的查询生成器中使用函数

提问于
浏览
-1

我有一个名为getValue的函数,它用于从数据库中的表中获取字符串值,它有3个参数

public static function getValue($entityId, $itemId, $langId){
    $value = EntityLocalization::select('value')
            ->where('entity_id' ,'=', $entityId)
            ->where('item_id', '=', $itemId)
            ->where('lang_id', '=', $langId)->first();   
    return $value;
}

我如何在查询生成器中使用此函数并从记录值中提供其参数 . 这是控制器中的查询构建器错误

$data['products'] = DB::table('products')
                                    ->join('entity_localizations', 'entity_localizations.item_id', '=', 'products.id')
                                    ->select('products.id as id',DB::raw('ifnull(entity_localizations.value ,products.name) as name'),
                                    'products.photo as photo','products.price as price',
                                    getValue(1, 'products.product_epartment_id',1) 
                                    ->where('entity_localizations.entity_id', '=', 1)
                                    ->get();

4 回答

  • 0

    您的 getValue 函数是 static 函数,您应该通过其相对类名 YourClassName::getValue(1, 'products.product_epartment_id',1) 调用该函数,或者如果函数与您使用查询的同一类,则可以使用 self 关键字( self::getValue(1, 'products.product_epartment_id',1) ) .

    如果您使用它的返回值作为 select 函数的参数,此函数也应返回单个字符串和有效列值 .

  • 0

    使用以下内容

    雄辩: selectRaw(getValue(...) . ' as someColumnName')

    否则: DB::raw();

  • 0

    我收到另一个错误>>未知列“函数的返回值”这里是添加DB :: raw()后的代码

    $data['products'] = DB::table('products')
                                    ->join('product_departments','product_departments.id','=','products.product_department_id')
                                    ->join('entity_localizations', 'entity_localizations.item_id', '=', 'products.id')
                                    ->select('products.id as id',DB::raw('ifnull(entity_localizations.value ,products.name) as name'),
                                    'products.photo as photo','products.price as price',
                                     DB::raw(Helper::getValue(1,4,1)->value) .' as product_department')
                                    ->where('entity_localizations.entity_id', '=', $entity_id->id)
                                    ->get();
    
  • 0

    您尝试使用的值可能与表字段名称不匹配 .

    正如Rohit写的那样,你应该返回一个字符串,你也可以使用 firstOrfail() 来抛出更精确的异常 . 然后你'll find out if you'得到null而不是实际值 .

    return EntityLocalization
      ::where('entity_id' ,'=', $entityId)
      ->where('item_id', '=', $itemId)
      ->where('lang_id', '=', $langId)
      ->firstOrFail()
      ->value;
    

    通过转储查询_47448进行调试,或者只是查看结果并检查数据库 . 确保您实际获得的值与表模式相对应 .

相关问题