标签: eager-loading

:是否包含ActiveRecord实例的工作?

以下所有示例:包括for eager loading用于类级别查询.我在我的模型实例上尝试了它,它仍然发出了一堆查询 - 它是否适用于实例方法?

 #in controller
 @emails = person.sent_emails(:include => [:recipient])

 #in view
 render @emails

 # _email.html.erb partial
 <h1><%= email.recipient.name %></h1>
 <p>
 <%= email.content %>
 </p>

 #still issues a select * for emails, N+1 for recipients :/
Run Code Online (Sandbox Code Playgroud)

activerecord ruby-on-rails eager-loading

6
推荐指数
1
解决办法
1352
查看次数

渴望通过has_many加载

我有一个User模特.

A user有很多integrations.

An integration连接到包含列的profilevia .integration_profilesdata

我想急切加载所有用户的个人资料.

class Integration < ActiveRecord::Base
 has_many :integration_profiles
 has_many :profiles, through: :integration_profiles
end

class IntegrationProfile < ActiveRecord::Base
 belongs_to :integration
 belongs_to :profile
end

class Profile < ActiveRecord::Base
 has_many :integration_profiles
 has_many :integrations, through: :integration_profiles
end
Run Code Online (Sandbox Code Playgroud)

我试过这个:

all = User.first.integrations.includes(:profiles)
Run Code Online (Sandbox Code Playgroud)

但是当我这样做的时候 all.count

=> 2
Run Code Online (Sandbox Code Playgroud)

但是,当我这样做

all = User.first.integrations.joins(:profiles)
all.count
=> the correct total
Run Code Online (Sandbox Code Playgroud)

我应该使用包含还是加入?我一直使用包括所以不确定为什么这不起作用

ruby-on-rails eager-loading ruby-on-rails-3 ruby-on-rails-4

6
推荐指数
1
解决办法
5223
查看次数

如何在Laravel Eager Loading中添加别名

当我做Laravel急切加载时我需要别名:

$posts = Post::with(array('images as main_image' => function($query) // do not run
            {
                $query->where('number', '=', '0');

            }))
            ->where('id', '=', $id)
            ->get();

return Response::json($posts);
Run Code Online (Sandbox Code Playgroud)

我需要这个,因为我想要这样的JSON响应:

[
  {
    "id": 126,
    "slug": "abc",
    "name": "abc",
    "created_at": "2014-08-08 08:11:25",
    "updated_at": "2014-08-28 11:45:07",
    "**main_image**": [
      {
        "id": 223,
        "post_id": 126
        ...
      }
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

有可能的?

eager-loading laravel eloquent

6
推荐指数
2
解决办法
4962
查看次数

Clojure传感器是否渴望?

在这篇博客文章"JavaScript中的CSP和传感器"中,作者指出:

首先,我们必须认识到许多数组(或其他集合)操作map,filter并且reverse可以用a来定义reduce.

那么我们在Clojure中看到一些这样的实现并不是懒惰的,他们渴望:

 user> (defn eager-map [f coll]
        (reduce (fn [acc v] (conj acc (f v)))
        []
        coll))
#'user/eager-map
user> (eager-map inc (range 10))
[1 2 3 4 5 6 7 8 9 10]
Run Code Online (Sandbox Code Playgroud)

我的问题是,Clojure传感器是否渴望?

reduce dictionary clojure eager-loading transducer

6
推荐指数
1
解决办法
839
查看次数

laravel - eloquent - 得到相关模型特定列的总和

假设我有桌子

命令

与领域

id,userId,amount,description

和桌子

用户

与各个领域

如果我想让所有用户(包括其所有字段)以及与该用户相关的订单的"金额"列的总和如何?

假设我有:

用户:{ID:15,姓:吉姆,名字:莫里森,性别:雄性}

order:{id:1,userId:15,amount:10,description:"order xxx"},

订单:{id:3,userId:15,金额:40,说明:"订购yyy"}

我想收到:

用户:{ID:15,姓:吉姆,名字:莫里森,性别:男性,orderAmount:50}

当然,我想避免使用foreach声明.

我已经在我的用户模型上设置了这个

public function userOrder (){
    return $this->hasMany('Order', 'userId');
}
Run Code Online (Sandbox Code Playgroud)

我试过这个:

return $this->hasMany('Order', 'userId')->sum('amount');
Run Code Online (Sandbox Code Playgroud)

没有运气......

eager-loading laravel eloquent

6
推荐指数
1
解决办法
2万
查看次数

Laravel 4.1急切加载

我在急切的装载上遇到了麻烦.假设我有会员模型,TrainingCategory,TrainingCategoryResult和Registration

会员型号:

public function registration() {
    return $this->hasMany('Registration', 'member_id');
}
public function trainingResults(){
    return $this->hasMany('trainingResult', 'member_id');
}
public function trainingCategoryResults() {
  return $this->hasMany('TrainingCategoryResult', 'member_id');
}
Run Code Online (Sandbox Code Playgroud)

TrainingCategory模型:

public function trainings() {
    return $this->hasMany('Training', 'id');
}
public function trainingCategoryResults() {
    return $this->hasMany('trainingCategoryResult', 'category_id');
}
Run Code Online (Sandbox Code Playgroud)

TraningCategoryResult模型:

  public function category() {
        return $this->belongsTo('TrainingCategory', 'id');
  }
  public function member() {
        return $this->belongsTo('Member', 'id');
  }
Run Code Online (Sandbox Code Playgroud)

注册模式:

  public function course() {
    return $this->belongsTo('Course', 'course_id');
  }
  public function member() {
    return $this->belongsTo('Member', 'id');
  }
Run Code Online (Sandbox Code Playgroud)

我试图加载所有注册信息及其相关信息,包括TraningCategoryResult信息,但我不知道如何获得需要两个外键(category_id和member_id)的TraningCategoryResult,有什么方法可以做到这一点?

这是我的代码atm:

 $members= Member::where(function($query) …
Run Code Online (Sandbox Code Playgroud)

php eager-loading laravel-4

6
推荐指数
1
解决办法
112
查看次数

Laravel的多级急切加载?

假设我有这些关系

class Invitation
{
    public function invitedPeople()
    {
        return $this->belongsTo('App\Person', 'personID');
    }
}

class Person 
{
    public function apartments()
    {
        return $this->belongsToMany('App\Apartment', 'apartment_person', 'personID', 'apartmentID');        
    }
}

class Apartment 
{
    public function city()
    {
        return $this->belongsTo('App\City', 'cityID');
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,使用Laravel eager loading时我们可以拥有多少个嵌套级别?我已经尝试过这个查询并且它无法正常工作,有人可以建议解决这个问题吗?

return Invitation::with(['invitedPeople', 'invitedPeople.apartments', 'invitedPeople.apartments.city'])
Run Code Online (Sandbox Code Playgroud)

php eager-loading laravel laravel-5

6
推荐指数
1
解决办法
1540
查看次数

addSelect()Builder方法如何在Laravel中工作

说我有这些模型:

用户模型

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'User';

    protected $fillable =
    [
       'username', 'favoriteColor'
    ];          

    public function flights()
    {
        return $this->hasMany('App\Flight');
    }
}
Run Code Online (Sandbox Code Playgroud)

飞行模型

namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'Flight';

    protected $fillable =
    [
       'flightName', 
    ];              
}   
Run Code Online (Sandbox Code Playgroud)

每当我这样做时,我都会尝试用急切的加载做一些事情:

$usersWithFlights = …
Run Code Online (Sandbox Code Playgroud)

php eager-loading laravel laravel-5

6
推荐指数
2
解决办法
1万
查看次数

渴望加载结果时,"TypeError:没有将nil隐式转换为String"

我正在使用ruby '2.3.0''rails', '3.2.22.2'.

我需要一些关于我所做查询的帮助和解释.这是我的模特:

class AssessmentRaw < ActiveRecord::Base
  belongs_to :session
  has_many :schedulers, :class_name => 'MailingScheduler', :as => :owner, :dependent => :destroy
end

class MailingScheduler < ActiveRecord::Base
  belongs_to :owner, :polymorphic => true
end

class Session < ActiveRecord::Base
  has_many :assessment_raws, :dependent => :destroy
end
Run Code Online (Sandbox Code Playgroud)

我想检索所有的assessment_raws,并急切加载关联的会话和mailing_schedulers.

1.急切加载会话

ars = AssessmentRaw.includes(:session).where("sessions.start_at >= ?", 1.year.ago).limit(10)

ars.map { |ar| ar.session.id } => [2877,2878,2879,2888,2881,2882,2883,2884,2902,2903]

`ars.map { |ar| ar.schedulers.try(:size) }`
   MailingScheduler Load (0.6ms)  SELECT "mailing_schedulers".* FROM "mailing_schedulers" WHERE "mailing_schedulers"."owner_id" = 622 AND "mailing_schedulers"."owner_type" = …
Run Code Online (Sandbox Code Playgroud)

activerecord outer-join eager-loading arel ruby-on-rails-3

6
推荐指数
1
解决办法
740
查看次数

Rails 4 - 使用eager_load选择

我正在尝试仅选择使用某些列eager_load,但我遇到的问题是它取消了我的'select'.

模型:

class Timeline < ActiveRecord::Base
    belongs_to :timeline_category, foreign_key: :timeline_category_id
    belongs_to :user, foreign_key: :user_id
    scope :with_relations, -> { eager_load(:timeline_category).eager_load(:user).order(created_at: :desc) 
end
Run Code Online (Sandbox Code Playgroud)

查询:

Timeline.select('timelines.*, users.username, timeline_categories.icon').eager_load(:timeline_category).eager_load(:user)
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

Timeline.select('timelines.*, users.username, timeline_categories.icon').with_relations
Run Code Online (Sandbox Code Playgroud)

出于某种原因,它会不断选择所有3个表的所有列.我该如何解决?

ruby-on-rails eager-loading

6
推荐指数
2
解决办法
1215
查看次数