GVKun编程网logo

使用DB :: raw和Eloquent使用同一查询的不同结果

15

在本文中,我们将带你了解使用DB::raw和Eloquent使用同一查询的不同结果在这篇文章中,同时我们还将给您一些技巧,以帮助您实现更有效的Eloquent条件查询——tucker-eric/elo

在本文中,我们将带你了解使用DB :: raw和Eloquent使用同一查询的不同结果在这篇文章中,同时我们还将给您一些技巧,以帮助您实现更有效的Eloquent 条件查询——tucker-eric/eloquentfilter 笔记、Laravel Eloquent ORM 多条件查询的例子、Laravel Eloquent vs查询构建器-为什么使用eloquent降低性能、Laravel Eloquent 数据查询结果中日期的格式化

本文目录一览:

使用DB :: raw和Eloquent使用同一查询的不同结果

使用DB :: raw和Eloquent使用同一查询的不同结果

运行Eloquent联接查询时,我得到了一些意外的结果。通过使用完全相同的查询,我得到两个不同的结果。一个使用DB ::
raw()运行,第二个使用Eloquent。

在口才查询中,与

where squad_user.leave_time >= seasons.start_time

丢失,将不会包含在结果集中。符合条件的用户

or squad_user.leave is null

但是将包括在内。

这是两个查询结果的唯一区别。原始查询实际上会产生所需的结果集。

什么 真正 困扰我的是,如果我检查查询日志,既Laravel的和MySQL,我同时运行原料和雄辩的查询时,得到完全相同的查询。

原始查询 (运行口才查询时,我从查询日志中获得的 实际 查询)

return \DB::select(\DB::raw(''        select users.*        from users        inner join squad_user on users.id = squad_user.user_id        inner join seasons on squad_user.squad_id = seasons.squad_id        where squad_user.join_time <= seasons.end_time        and (squad_user.leave_time >= seasons.start_time or squad_user.leave_time is null)        and seasons.id = :seasonId    ''),    [''seasonId'' => 3]);

口才查询

return User::join(''squad_user'', ''users.id'', ''='', ''squad_user.user_id'')           ->join(''seasons'', ''squad_user.squad_id'', ''='', ''seasons.squad_id'')           ->where(''squad_user.join_time'', ''<='', ''seasons.end_time'')           ->where(function ($query)           {               $query->where(''squad_user.leave_time'', ''>='', ''seasons.start_time'')                     ->orWhereNull(''squad_user.leave_time'');           })           ->where(''seasons.id'', 3)           ->get([''users.*'']);

Laravel雄辩的查询日志

select `users`.*from `users`inner join `squad_user` on `users`.`id` = `squad_user`.`user_id`inner join `seasons` on `squad_user`.`squad_id` = `seasons`.`squad_id`where `squad_user`.`join_time` <= seasons.end_timeand (`squad_user`.`leave_time` >= seasons.start_time or `squad_user`.`leave_time` is null)and `seasons`.`id` = 3{"bindings":["seasons.end_time","seasons.start_time",3],"time":0.38,"name":"mysql"}

MySQL的Eloquent查询的general_log

select `users`.*from `users`inner join `squad_user` on `users`.`id` = `squad_user`.`user_id`inner join `seasons` on `squad_user`.`squad_id` = `seasons`.`squad_id`where `squad_user`.`join_time` <= ?and (`squad_user`.`leave_time` >= ? or `squad_user`.`leave_time` is null)and `seasons`.`id` = ?

MySQL在raw查询上的general_log

select users.*            from users            inner join squad_user on users.id = squad_user.user_id            inner join seasons on squad_user.squad_id = seasons.squad_id            where squad_user.join_time <= seasons.end_time            and (squad_user.leave_time >= seasons.start_time or squad_user.leave_time is null)            and seasons.id = ?

我会很感激这里的任何指示,因为我很失落。

答案1

小编典典

where绑定第三参数并将其通常视为字符串,除非您通过使用raw语句告诉它不这样做。DB::rawwhereRaw将为您工作:

return User::join(''squad_user'', ''users.id'', ''='', ''squad_user.user_id'')       ->join(''seasons'', ''squad_user.squad_id'', ''='', ''seasons.squad_id'')       ->where(''squad_user.join_time'', ''<='', DB::raw(''seasons.end_time''))       ->where(function ($query)       {           $query->where(''squad_user.leave_time'', ''>='', DB::raw(''seasons.start_time''))                 ->orWhereNull(''squad_user.leave_time'');       })       ->where(''seasons.id'', 3)       ->get([''users.*'']);

Eloquent 条件查询——tucker-eric/eloquentfilter 笔记

Eloquent 条件查询——tucker-eric/eloquentfilter 笔记

请阅读 https://github.com/Tucker-Eric/EloquentFilter , 里面有很全的文档和注释,以下仅列出关键部分。

 

1. 安装

composer require tucker-eric/eloquentfilter

  

2. 添加Provider 

在 config/app.php 中添加  EloquentFilter\ServiceProvider::class

''providers'' => [
    // Other service providers...

    EloquentFilter\ServiceProvider::class,
],

  

3. 添加配置 

php artisan vendor:publish --provider="EloquentFilter\ServiceProvider"

  在 config 下出现 eloquentfilter.php 。 

注意配置文件中 命名空间配置

''namespace'' => "App\\ModelFilters\\",

  默认会读取该命名空间下类,若使用其他命名空间类,需要修改该配置,或者传入该类 。 

//使用默认命名空间 
Post::filter([''title''=>''23''])->get();
//指定类
$userFilter = App\ModelFilters\User\UserFilter::class;
User::filter($input, $userFilter)->get();

  ,或者在Model 中指定(下面会提到)。

4. 修改Model

以User 为例

namespace App;

//必须引入 use EloquentFilter\Filterable; use Illuminate\Database\Eloquent\Model; class User extends Model {
  //使用Trait , 其中有 scopeFilter, 以便可以静态调用, User::filter use Filterable;
  //指定使用的过滤类 public function modelFilter() { return $this->provideFilter(App\ModelFilters\User\UserFilter::class); } //User Class }

  

5. 使用

5.1 动态过滤

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
use App\ModelFilters\Admin\UserFilter as AdminFilter;
use App\ModelFilters\User\UserFilter as BasicUserFilter;
// 若没有添加alias , 参考 github 上文档会找不到类 use Illuminate\Support\Facades\Auth; class UserController extends Controller { public function index(Request $request) { $userFilter = Auth::user()->isAdmin() ? AdminFilter::class : BasicUserFilter::class; return User::filter($request->all(), $userFilter)->get(); } }

  

文档中提高了很多功能和配置,这里不再复述,有不对的地方请指正!

 

 

 

 

补充: 

1. User 表结构

CREATE TABLE `users`  (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `phone` varchar(11) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `remember_token` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  `created_at` timestamp(0) NULL DEFAULT NULL,
  `updated_at` timestamp(0) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 10 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Compact;

2. Filterable 源码

trait Filterable
{

   /**
     * Creates local scope to run the filter.
     *
     * @param $query
     * @param array $input
     * @param null|string|ModelFilter $filter
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeFilter($query, array $input = [], $filter = null)
    {
        // Resolve the current Model''s filter
        if ($filter === null) {
            $filter = $this->getModelFilterClass();
        }

        // Create the model filter instance
        $modelFilter = new $filter($query, $input);

        // Set the input that was used in the filter (this will exclude empty strings)
        $this->filtered = $modelFilter->input();

        // Return the filter query
        return $modelFilter->handle();
    }
}

  

 

3.  UserFilter 代码

use EloquentFilter\ModelFilter;

class UserFilter extends ModelFilter {

  /**
   * 关联查询中使用 * Related Models that have ModelFilters as well as the method on the ModelFilter * As [relationMethod => [input_key1, input_key2]]. * 具有ModelFilters的相关模型以及ModelFilter上的方法 如[relationMethod => [input_key1,input_key2]]。
* @var array
    */
    public $relations = [];

  // 黑名单
// 过滤器不会调用blackist数组中定义的任何方法。这些方法通常用于内部过滤器逻辑
  protected $blacklist = [''secretMethod''];

   /**

  *  过滤是以表字段-方法,做了映射,
  */
// User 表中字段 email public function email($email) { return $this->where(''email'', ''='', $email); }   // User 表中字段 public function name($name) { return $this->where(function($q) use ($name) { return $q->where(''name'', ''LIKE'', "%$name%"); }); } // User 表中字段名 public function phone($phone) { return $this->where(''phone'', ''LIKE'', "%$phone%"); }   //每次filter,都会调用,非必需(参考 ModelFilter->filter ) public function setup() { $this->onlyShowDeletedForAdmins();
     //$this->xxx(); } public function onlyShowDeletedForAdmins() { if(Auth::user()->isAdmin()) { //$this->withTrashed(); } }    // public function secretMethod($secretParameter) { return $this->where(''some_column'', true); }

 

4.  父类  EloquentFilter\ModelFilter

use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\Builder as QueryBuilder;

/**
 * @mixin QueryBuilder
 */
abstract class ModelFilter
{

/**
     * ModelFilter constructor.
     *
     * @param $query
     * @param array $input
     * @param bool $relationsEnabled
     */
    public function __construct($query, array $input = [], $relationsEnabled = true)
    {
        $this->query = $query;
        $this->input = $this->removeEmptyInput($input);
        $this->relationsEnabled = $relationsEnabled;
        $this->registerMacros();
    }

    /**
     * @param $method
     * @param $args
     * @return mixed
     */
    public function __call($method, $args)
    {
        $resp = call_user_func_array([$this->query, $method], $args);

        // Only return $this if query builder is returned
        // We don''t want to make actions to the builder unreachable
        return $resp instanceof QueryBuilder ? $this : $resp;
    }

/**
     * Handle all filters.
     *
     * @return QueryBuilder
     */
    public function handle()
    {
        // Filter global methods
        if (method_exists($this, ''setup'')) {
            $this->setup();
        }

        // Run input filters
        $this->filterInput();
        // Set up all the whereHas and joins constraints
        $this->filterRelations();

        return $this->query;
    }

}

  

 

Laravel Eloquent ORM 多条件查询的例子

Laravel Eloquent ORM 多条件查询的例子

一、需求:

在数据搜索时最常见的就是调用同一个方法查询,而查询的字段却可能是其中一个或其中的几个字段一起组合查询,例如:对列表的搜索,基本上都是几个字段随意组合搜索。那么在model里就需要判断有那个字段组合,怎么组合。

网上找了很久,Laravel群里也问了几个,都说没有写过,于是自己写个吧。话不多说,见代码:

function findByParam($param = array()) 
 { 
  $select = new Customer(); 
  if (isset($param[''name'']) && '''' != $param[''name'']) 
  { 
   $select = $select->where(''customer.name'', ''='', $param[''name'']); 
  } 
  if (isset($param[''phone'']) && '''' != $param[''phone'']) 
  { 
   $select = $select->where(''customer.phone'', ''='', $param[''phone'']); 
  } 
  if (isset($param[''email'']) && '''' != $param[''email'']) 
  { 
   $select = $select->where(''customer.email'', ''='', $param[''email'']); 
  } 
  if (isset($param[''tel'']) && '''' != $param[''tel'']) 
  { 
   $select = $select->where(''customer.tel'', ''='', $param[''tel'']); 
  } 
  if (isset($param[''qq'']) && '''' != $param[''qq'']) 
  { 
   $select = $select->where(''customer.qq'', ''='', $param[''qq'']); 
  } 
  if (isset($param[''IDCard'']) && '''' != $param[''IDCard'']) 
  { 
   $select = $select->where(''customer.IDCard'', ''='', $param[''IDCard'']); 
  } 
   
  $customers = $select->leftJoin("member", function ($join) 
  { 
   $join->on("customer.memberID", "=", "member.id"); 
  }) 
   ->get(array( 
   ''customer.id'', 
   ''customer.name'', 
   ''customer.sex'', 
   ''customer.tel'', 
   ''customer.phone'', 
   ''customer.address'', 
   ''customer.email'', 
   ''customer.qq'', 
   ''customer.headPic'', 
   ''customer.birthday'', 
   ''customer.IDCard'', 
   ''customer.enable'', 
   ''customer.memberID'', 
   ''customer.IDCard'', 
   ''customer.info'', 
   ''member.name as mname'', 
   ''member.discount'' 
  )); 
  return json_encode($customers); 

调用的时候,controller里只需要接收这些字段,无论它是否有值,直接加入到$param数组中查询就OK,例如:

function anyFindbyparam() 
 { 
  $name = Input::get(''name''); 
  $tel = Input::get(''tel''); 
  $phone = Input::get(''phone''); 
  $email = Input::get(''email''); 
  $qq = Input::get(''qq''); 
  $IDCard = Input::get(''IDCard''); 
  $customer = new Customer(); 
  $customers = $customer->findByParam(array( 
   ''name'' => $name, 
   ''tel'' => $tel, 
   ''phone'' => $phone, 
   ''email'' => $email, 
   ''qq'' => $qq, 
   ''IDCard'' => $IDCard 
  )); 
  return $customers; 
 } 

以上这篇Laravel Eloquent ORM 多条件查询的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

您可能感兴趣的文章:
  • Laravel5.7 Eloquent ORM快速入门详解
  • Laravel 5框架学习之Eloquent (laravel 的ORM)
  • Laravel Eloquent ORM 实现查询表中指定的字段
  • laravel 解决Eloquent ORM的save方法无法插入数据的问题
  • Laravel框架Eloquent ORM新增数据、自定义时间戳及批量赋值用法详解
  • laravel框架数据库操作、查询构建器、Eloquent ORM操作实例分析
  • Laravel框架Eloquent ORM删除数据操作示例
  • laravel 数据迁移与 Eloquent ORM的实现方法
  • Laravel框架Eloquent ORM简介、模型建立及查询数据操作详解
  • Laravel框架Eloquent ORM修改数据操作示例
  • laravel5.6 框架操作数据 Eloquent ORM用法示例

Laravel Eloquent vs查询构建器-为什么使用eloquent降低性能

Laravel Eloquent vs查询构建器-为什么使用eloquent降低性能

已关闭 。这个问题需要更加集中。它当前不接受答案。


想改善这个问题吗? 更新问题,使其仅通过编辑此帖子来关注一个问题。

6个月前关闭。

我在Laravel查询生成器和雄辩者之间进行了一些性能测试。使用各种sql语句(select-update-delete-
insert),查询生成器要快得多。

所以我的问题是:为什么有人对普通查询生成器使用Laravel Eloquent?

答案1

小编典典

雄辩的是Laravel的Active Record模式的实现,它具有所有优点和缺点。

Active Record是用于以CRUD方式处理单个实体的好解决方案-即创建具有填充属性的新实体,然后将其保存到数据库,从数据库加载记录或删除。

您将从Eloquent的功能中受益匪浅,例如脏检查(仅针对已更改的字段发送SQL
UPDATE),模型事件(例如,在有人创建新帐户时发送管理警报或更新统计信息计数器),特征(时间戳,软删除,自定义特征)急切/延迟加载等。您还可以应用域驱动模式并在Active
Record实体中实现一些业务逻辑,例如验证,管理关系,计算等。

但是,正如您已经知道的那样,Active Record附带了一些性能价格。

当您处理一条记录或几条记录时,无需担心。但是对于读取大量记录的情况(例如,用于数据网格,用于报告,用于批处理等),普通的Laravel
DB方法是更好的方法。

对于基于Laravel的应用程序,我们认为合适的是同时使用两种方法。我们使用Laravel的Eloquent for
UI表单来处理一条记录,并使用DB方法(由SQL视图支持,并进行了其他数据库引擎特定的性能调整)来检索UI表,导出任务等的数据。它还与RESTful
API配合使用-Eloquent for GET ,PUT,POST,DELETE(带键),DB而GET(不带键)但具有过滤器,排序和分页。

Laravel Eloquent 数据查询结果中日期的格式化

Laravel Eloquent 数据查询结果中日期的格式化

两种情况:

使用 Model 的查询

例如:

$item = App\Models\Apple::first();
$date = $item->created_at->format(''Y-m-d'');

使用 DB::table 的查询

如果直接对结果中的 datetime 做 format,会报错

Call to a member function format() on string

因为 DB::table 返回的结果都是 string,没有关联 Model。当然各种定义好的自动转换也会失效。

这时候就需要先解析,再格式化

Carbon\Carbon::parse($item->expired_at)->format(''Y-m-d'')

最佳方案

所以,尽量使用 Model 进行数据查询操作,避免使用 DB::table.

即使是使用 leftJoin 这些操作,也可以是 Model 进行。虽然官方文档一直在用 DB::table.

例如:

$case->progress_detail = ProjectProgress::leftJoin(''users'', ''project_progress.pm_id'', ''='', ''users.id'')
                ->select(''project_progress.*'', ''users.name'')
                ->where(''project_progress.id'', $case->id)
                ->first();

关于使用DB :: raw和Eloquent使用同一查询的不同结果的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于Eloquent 条件查询——tucker-eric/eloquentfilter 笔记、Laravel Eloquent ORM 多条件查询的例子、Laravel Eloquent vs查询构建器-为什么使用eloquent降低性能、Laravel Eloquent 数据查询结果中日期的格式化等相关内容,可以在本站寻找。

本文标签: